最近几天我一直在处理一些代码,用于将PostgreSQL连接到Android Studio。我用oneClickListener做了一个按钮,单击后应该进行查询。但是,当我运行该程序时,出现一些错误,我无法弄清楚为什么,我确实安装了Postgresql驱动程序并将其放入。另外,如果您已成功将Postgres连接到Android Studio,您如何做到这一点?
public static void test(){
}
/* This method return java.sql.Connection object. */
@SuppressWarnings("finally")
public String getPostgreSQLConnection()
{
/* Declare and initialize a sql Connection variable. */
Connection ret = null;
String output = "";
try
{
/* Register jdbc driver class. */
Class.forName("org.postgresql.Driver");
/* Create connection url. */
String mysqlConnUrl = "jdbc:postgresql://localhost/Student";
/* user name. */
String mysqlUserName = "postgres";
/* password. */
String mysqlPassword = "asd";
/* Get the Connection object. */
ret = DriverManager.getConnection(mysqlConnUrl, mysqlUserName , mysqlPassword);
/* Get related meta data for this mysql server to verify db connect successfully.. */
DatabaseMetaData dbmd = ret.getMetaData();
String dbName = dbmd.getDatabaseProductName();
String dbVersion = dbmd.getDatabaseProductVersion();
String dbUrl = dbmd.getURL();
String userName = dbmd.getUserName();
String driverName = dbmd.getDriverName();
//STEP 4: Execute a query
System.out.println("Creating statement...");
java.sql.Statement st = null;
st = ret.createStatement();
String sql;
sql = "INSERT INTO \"UserAccount\".\"UserInfo\"(\n" +
"\t\"UserName\", \"Password\", \"ID\")\n" +
"\tVALUES ('ss', 'string', 7)";
//sql = "SELECT * FROM \"UserAccount\".\"UserInfo\"";
ResultSet rs = st.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String first = rs.getString("UserName");
String last = rs.getString("Password");
//Display values
output.concat(first + last);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
st.close();
ret.close();
}catch(Exception ex)
{
ex.printStackTrace();
}finally
{
return output;
}
}