首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android studio与postgresql的连接

Android studio与postgresql的连接
EN

Stack Overflow用户
提问于 2017-05-16 16:32:09
回答 4查看 16.8K关注 0票数 0

我是android的新手,对此知之甚少。我虽然已经通过了教程,但仍然没有得到任何解决方案。如何连接Android Studio和postgressql?循序渐进!我在我的MainActitvity.java中写了这段代码。这是正确的吗?或者我应该把它写在别的地方?

代码语言:javascript
复制
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
    }
}
EN

回答 4

Stack Overflow用户

发布于 2017-12-10 11:41:14

使用10.0.2.2而不是localhost,它适用于我。

票数 2
EN

Stack Overflow用户

发布于 2017-05-16 16:43:50

安卓系统不能直接使用java.sql.DriverManger, Connection, etc。安卓支持SQLite DB,如果你想在安卓中使用DB,你必须使用SQLite数据库。对于Postgres,您必须开发服务器端应用程序和api服务,您可以从Android调用这些服务

票数 1
EN

Stack Overflow用户

发布于 2017-05-16 16:36:25

我的应用使用PostgreSQL作为后端。使用改良库连接到后端。在我的应用程序中,后端是用python编写的,它将在数据库中进行查询。这将使前端代码更加流畅和安全。并且可以将更多的控制转移到后端。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43996263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档