Android Studio 与 postgresql 的连接

问题描述 投票:0回答:5

我是android新手,对此不太了解。我虽然已经完成了教程,但仍然没有得到任何解决方案。如何将Android Studio与postgressql连接?一步步! 我在 MainActivity.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
    }
}
android database postgresql android-studio
5个回答
2
投票

使用 10.0.2.2 而不是 localhost,它对我有用。


1
投票

好吧,这可能已经过时,但对用户仍然有帮助(这对我很有帮助) 我复制了你的示例并使用它,因为我还需要让 postgres 在 android 上运行。它有效!

  1. conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","root","root");

这将导致错误,因为您需要输入数据库名称,并且在 and 处不带斜杠,例如:

conn = DriverManager.getConnection("jdbc:postgresql://domain.com:5432/databaseName", "username", "password");
  1. 网络连接(如数据库连接)必须在 AsyncTask 中使用 doInBackground() 完成。我在活动中完成了

    public class dbactivity extends AppCompatActivity { //sry code formatting just broke
    
    String message = null;
    String conmsg  = null;
    
    private class pgsqlcon extends AsyncTask<Void, Void, Void>
    {
    
        public pgsqlcon()
        {
            super();
        }
    
        @Override
        protected Void doInBackground(Void... voids) {
            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...");
                message = "Connecting to database...";
                conn = DriverManager.getConnection("jdbc:postgresql://serverdomain.com:5432/databasename",
    

    “数据库用户名”,“密码”); //等等

  2. 如果需要像setText那样进行UI更改,则必须像这样使用runOnUiThread():

//using quote because code formatting doesn't work anymore for me xD
    private void setAsyncText(final TextView text,final String value){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (value == null)
                text.setText("null");
            else
                text.setText(value);
        }
    });
    }
  1. 哦,是的,最后但并非最不重要的一点是,由于我在 Activity 中编写了此内容,因此我必须通过在 Activity 的 OnCreate() 中调用异步任务来触发问题。

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dbactivity);
    
        pgsqlcon pgcon = new pgsqlcon();
        pgcon.execute();
    }
    

    }

我自己没有那么丰富的经验,所以你只能使用它来仅使用 JDBC 来连接到你的 postgresdb。尽管我设法通过这种方式获得成功的查询结果。 再次对错误的代码格式表示歉意。我做了他们想要的(4 空间规则等),但它不起作用。无论如何,我希望你能读到它,祝你好运。

如果这些都不起作用,也许你想看看这些小提示:https://jdbc.postgresql.org/documentation/head/prepare.html (我假设你已经这样做了,因为你已经做了很多几乎正确的代码)


0
投票

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


0
投票

您无法直接与android studio连接数据库, 你必须通过 api 与你的应用程序和数据库建立连接, 你可以用java、php等编写你的api。

?php
  $db_connection = pg_connect("host=localhost dbname=record user=postgres password= ''");

  //pg query
?>

这是您的连接查询 API。


0
投票

您无法在 Android 中直接使用

java.sql.DriverManger, Connection, etc
。 Android支持SQLite DB,如果你想在android中使用DB,你必须使用SQLite数据库。对于 Postgres,您必须开发服务器端应用程序和 api 服务,然后您可以从 Android 调用它们。

© www.soinside.com 2019 - 2024. All rights reserved.