我是android的新手,对此知之甚少。我虽然已经通过了教程,但仍然没有得到任何解决方案。如何连接Android Studio和postgressql?循序渐进!我在我的MainActitvity.java中写了这段代码。这是正确的吗?或者我应该把它写在别的地方?
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:5432/user1";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args)
{
Connection conn = null;
Statement st = null;
try{
//STEP 2: Register JDBC driver
Class.forName("org.postgresql.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","root","root");
//STEP 4: Execute a query
System.out.println("Creating statement...");
st = conn.createStatement();
String sql;
sql = "SELECT first, last FROM Employees";
ResultSet rs = st.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
st.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally
{
//finally block used to close resources
try{
if(st!=null)
st.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}
}
发布于 2017-12-10 11:41:14
使用10.0.2.2而不是localhost,它适用于我。
发布于 2017-05-16 16:43:50
安卓系统不能直接使用java.sql.DriverManger, Connection, etc
。安卓支持SQLite DB,如果你想在安卓中使用DB,你必须使用SQLite数据库。对于Postgres,您必须开发服务器端应用程序和api服务,您可以从Android调用这些服务
发布于 2017-05-16 16:36:25
我的应用使用PostgreSQL作为后端。使用改良库连接到后端。在我的应用程序中,后端是用python编写的,它将在数据库中进行查询。这将使前端代码更加流畅和安全。并且可以将更多的控制转移到后端。
https://stackoverflow.com/questions/43996263
复制相似问题