Android Studio中Java连接PostgreSQL失败问题求助
连接PostgreSQL到Android Studio的问题排查
我是Java和SQL新手,尝试在Android Studio中通过Java连接PostgreSQL,但遇到以下问题:
- 存在未使用导入语句、ConnectPG类及相关方法未被使用的警告
- 单独调试InsertRecordExample文件时,出现Gradle构建错误:无法创建任务':app:InsertRecordExample.main()',找不到名为'main'的SourceSet
- 运行整个项目时无明显错误,但仅显示上述未使用相关的警告,ConnectPG连接类和InsertRecordExample插入类均无法正常工作
警告信息
Unused import statement Class 'ConnectPG' is never used Method 'connectBD()' is never used Method 'disconnection(java.sql.Connection)' is never used
Gradle错误详情
16:53:59: Executing ':app:InsertRecordExample.main()'...
FAILURE: Build failed with an exception.
- 位置:初始化脚本'C:\Users\fff\AppData\Local\Temp\InsertRecordExample_main__.gradle'第41行
- 问题:配置项目':app'时出错,无法创建任务':app:InsertRecordExample.main()',找不到名为'main'的SourceSet。
相关代码
ConnectPG.java
package com.example.a112new; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; public class ConnectPG { Connection connect=null; public Connection connectBD(){ try{ Class.forName("org.postgresql.Driver"); // localhost connect=DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/112", "postgresql", "430890"); }catch (Exception er) { System.err.println(er.getMessage()); } return connect; } // protected void disconnection(Connection con)throws Exception { con.close(); } }
InsertRecordExample.java
package com.example.a112new; //package net.javaguides.postgresql.tutorial; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Insert PrepareStatement JDBC Example * * @author Ramesh Fadatare * */ public class InsertRecordExample { //localhost private final String url = "jdbc:postgresql://127.0.0.1:5432/112"; private final String user = "postgres"; // root private final String password = "111111"; private static final String INSERT_USERS_SQL = "INSERT INTO users" + " (user_id, lastname, firstname, patronymic, birth,phone,email,password) VALUES "+" (?, ?, ?, ?, ?, ?, ?, ?);"; public static void main(String[] argv) throws SQLException { InsertRecordExample createTableExample = new InsertRecordExample(); createTableExample.insertRecord(); } public void insertRecord() throws SQLException { System.out.println(INSERT_USERS_SQL); // Step 1: Establishing a Connection try (Connection connection = DriverManager.getConnection(url, user, password); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) { preparedStatement.setInt(1, 1); preparedStatement.setString(2, "FFFF"); preparedStatement.setString(3, "FFFF"); preparedStatement.setString(4, "FFFFF"); preparedStatement.setString(5, "2005-01-12"); preparedStatement.setString(6, "+79888888888"); preparedStatement.setString(7, "11111@gmail.com"); preparedStatement.setString(8, "1234567"); System.out.println(preparedStatement); // Step 3: Execute the query or update query preparedStatement.executeUpdate(); } catch (SQLException e) { // print SQL exception information printSQLException(e); } // Step 4: try-with-resource statement will auto close the connection. } public static void printSQLException(SQLException ex) { for (Throwable e: ex) { if (e instanceof SQLException) { e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException) e).getSQLState()); System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); System.err.println("Message: " + e.getMessage()); Throwable t = ex.getCause(); while (t != null) { System.out.println("Cause: " + t); t = t.getCause(); } } } }}
解决方案
1. 解决Gradle构建错误(单独运行类的问题)
Android Studio的默认安卓项目结构没有main SourceSet用于直接运行带有main方法的类,因为安卓应用的入口是Activity而非普通Java类的main方法。有两种测试方式:
- 方式一:创建Java Library模块
在项目中新建一个Java Library模块,把ConnectPG和InsertRecordExample移到该模块下,即可直接运行带有main方法的类。 - 方式二:在安卓项目中通过Activity触发执行
在安卓的某个Activity中调用InsertRecordExample的insertRecord方法,注意必须放在子线程(安卓禁止主线程执行数据库操作):// 在Activity的onCreate方法中添加 new Thread(() -> { try { new InsertRecordExample().insertRecord(); } catch (SQLException e) { InsertRecordExample.printSQLException(e); } }).start();
2. 解决未使用警告问题
- 移除
ConnectPG中未使用的import java.sql.Driver;导入语句 - 在
InsertRecordExample的insertRecord方法中改用ConnectPG获取连接,让类和方法被调用:public void insertRecord() throws SQLException { System.out.println(INSERT_USERS_SQL); ConnectPG connectPG = new ConnectPG(); try (Connection connection = connectPG.connectBD(); PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) { // 保留原有的参数设置和执行代码 preparedStatement.setInt(1, 1); preparedStatement.setString(2, "FFFF"); // ...其他参数设置 preparedStatement.executeUpdate(); } catch (SQLException e) { printSQLException(e); } catch (Exception e) { e.printStackTrace(); } }
3. 其他必要配置
- 在
app/build.gradle中添加PostgreSQL JDBC依赖:dependencies { // 其他依赖 implementation 'org.postgresql:postgresql:42.7.3' // 使用最新稳定版本 } - 确保本地PostgreSQL服务处于运行状态,数据库
112存在,用户名和密码正确 - 安卓9及以上版本需在
AndroidManifest.xml的application标签中添加明文连接许可:android:usesCleartextTraffic="true"
内容的提问来源于stack exchange,提问作者user20229409
相关产品推荐
相关产品推荐

