与 postgresql 的 Android Studio 连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43996263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:34:20  来源:igfitidea点击:

Android studio connectivity with postgresql

androiddatabasepostgresqlandroid-studio

提问by example one

I'm new to android and not much aware about it. I though have been through tutorial but still didn't get any solution. How to connect Android Studio with postgressql? Step by step! I wrote this code in my MainActitvity.java. Is this correct? Or should I write it else where?

我是 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
    }
}

回答by Mrinmoy

You cannot directly use java.sql.DriverManger, Connection, etcin Android. Android support SQLite DB, if you want to use DB in android you have to go with SQLite database. For Postgres you have to develop server side application and api services which you can the call from Android

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

回答by Medhanie W.

use 10.0.2.2 instead of localhost, it works for me.

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

回答by Sawk Medic

Okay, this may be obsolete but still helpful for users (it was helpful for me) I copied your example and worked with it because I also need to get postgres running on android. And it works!

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

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

This will result in an error because you need to enter the database name without a slash at the and, like:

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

conn = DriverManager.getConnection("jdbc:postgresql://domain.com:5432/databaseName", "username", "password");
  1. Network connections (like connection to database) must be done in an AsyncTask using doInBackground(). I did it inside an activity

    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",
    

    "dbusername", "password"); //and so on

  2. If you need to make UI changes like setText, you must use runOnUiThread like so ():

  1. 必须使用 doInBackground() 在 AsyncTask 中完成网络连接(如连接到数据库)。我在一个活动中做的

    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",
    

    "dbusername", "密码"); //等等

  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);
        }
    });
    }
//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. Oh yeah and last but not least, since I wrote this inside an Activiy, I have to trigger the trouble by calling my asynctask in OnCreate() of my Activity.

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

    }

  1. 哦,是的,最后但并非最不重要的一点,因为我在 Activiy 中写了这个,所以我必须通过在我的 Activity 的 OnCreate() 中调用我的异步任务来触发问题。

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

    }

I am not that experienced by myself so you can use this only for getting a connection at all to your postgresdb using JDBC only. Although I managed to get successful query results that way. And again, sorry for the wrong code formatting. I did what they wanted (4 space rule etc.) and it didn't work. I hope you can read it anyway, good luck.

我自己并没有那么有经验,因此您只能使用它来仅使用 JDBC 完全连接到您的 postgresdb。尽管我设法通过这种方式获得了成功的查询结果。再次,对于错误的代码格式感到抱歉。我做了他们想做的事(4 个空格规则等),但没有奏效。我希望你无论如何都能读到它,祝你好运。

And if nothing of this does work, maybeeee you want to take a look at these little hints: https://jdbc.postgresql.org/documentation/head/prepare.html(I assume you did that anyway since you have done a lot of almost correct code)

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

回答by Ankur Rawat

You can not connect the database with android studio directly, you have to make connection with your application and database through api , and you can write your api in java, php etc.

你不能直接用android studio连接数据库,你必须通过api连接你的应用程序和数据库,你可以用java,php等编写你的api。

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

  //pg query
?>

This is your connect query api.

这是您的连接查询 API。

回答by Athul Antony NP

My app uses PostgreSQL as backend. Use the retrofit library for connecting to the backend. In my app backend is written in python which will make queries in the database. This will make the front-end codes more smooth and secure. And the more controls can be shifted to the back-end.

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