简体   繁体   English

Android Studio 与 postgresql 的连接

[英]Android studio connectivity with postgresql

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?如何将 Android Studio 与 postgressql 连接? Step by step!一步步! I wrote this code in my MainActitvity.java.我在 MainActitvity.java 中编写了这段代码。 Is this correct?这样对吗? Or should I write it else where?还是我应该在其他地方写?

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

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

You cannot directly use java.sql.DriverManger, Connection, etc in Android. Android 中不能直接使用java.sql.DriverManger, Connection, etc Android support SQLite DB, if you want to use DB in android you have to go with SQLite database. Android 支持 SQLite DB,如果你想在 android 中使用 DB,你必须使用 SQLite 数据库。 For Postgres you have to develop server side application and api services which you can the call from Android对于 Postgres,您必须开发服务器端应用程序和 api 服务,您可以从 Android 调用这些服务

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.好的,这可能已经过时,但对用户仍然有帮助(这对我有帮助)我复制了您的示例并使用它,因为我还需要在 android 上运行 postgres。 And it works!它有效!

  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().必须使用 doInBackground() 在 AsyncTask 中完成网络连接(如连接到数据库)。 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"); "dbusername", "密码"); //and so on //等等

  2. If you need to make UI changes like setText, you must use runOnUiThread like so ():如果您需要像 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. 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.哦,是的,最后但并非最不重要的一点是,由于我在 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.我自己并没有那么有经验,因此您只能使用它来仅使用 JDBC 连接到您的 postgresdb。 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.我做了他们想做的事情(4 个空格规则等),但没有奏效。 I hope you can read it anyway, good luck.我希望你无论如何都能读到它,祝你好运。

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(我假设你无论如何都这样做了,因为你做了很多几乎正确的代码)

My app uses PostgreSQL as backend.我的应用程序使用 PostgreSQL 作为后端。 Use the retrofit library for connecting to the backend.使用改造库连接到后端。 In my app backend is written in python which will make queries in the database.在我的应用程序后端是用 python 编写的,它将在数据库中进行查询。 This will make the front-end codes more smooth and secure.这将使前端代码更加流畅和安全。 And the more controls can be shifted to the back-end.并且更多的控件可以转移到后端。

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM