首页 > 解决方案 > 如何将 android 应用程序 kotlin 连接到 Postgresql

问题描述

我在学校做一个项目,我需要将网站和我的 android 应用程序连接到 PostgreSQL 数据库,我尝试使用 JDBC 直接连接,但它根本不起作用。我也读过有关使用某些 API 的信息,但我不明白该怎么做我现在不知道该怎么做有人知道如何将 android 应用程序连接到 PostgreSQL 吗?我将永远感激我真的需要完成这个项目。

编辑:jdbc 的问题是控制台总是打印“连接失败”这是我的 JDBC 尝试

import java.sql.DriverManager

class Database {
    private var connection: Connection? = null
    private val host = "i replaced this so i dont lose controll over the database*eu-west-1.compute.amazonaws.com" // For Google Cloud Postgresql
    private val database = "*****mcl8"
    private val port = ****
    private val user = "****wwzntag"
    private val pass = "*****2c82a7dd7"
    private var url = "jdbc:postgresql://xhlgovzwwzntag:ccf199dc***********cb6a1865e87e7532da842c82a7dd7@ec2-34-255-134-200.eu-west-1.compute.amazonaws.com:5432/d2rlvf0bcqmcl8"
    private var status = false
    private fun connect() {
        val thread = Thread {
            try {
                Class.forName("org.postgresql.Driver")
                connection = DriverManager.getConnection(url, user, pass)
                status = true
                println("connected:$status")
            } catch (e: Exception) {
                status = false
                print(e.message)
                e.printStackTrace()
            }
        }
        thread.start()
        try {
            thread.join()
        } catch (e: Exception) {
            e.printStackTrace()
            status = false
        }
    }

    val extraConnection: Connection?
        get() {
            var c: Connection? = null
            try {
                Class.forName("org.postgresql.Driver")
                c = DriverManager.getConnection(url, user, pass)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return c
        }

    init {
        url = String.format(url, host, port, database)
        connect()
        //this.disconnect();
        println("connection status:$status")
    }
}```

标签: javaandroidpostgresqlkotlin

解决方案


答案很简单,就像@cutiko 说我需要创建一个rest API(这是一个直接与数据库连接的后端网站,然后我将数据发送到网站,该网站与网站进行其余的通信数据库)[解释其工作原理的图像][1]

为了制作我使用node.js、express 和 sequilize的 Api ,这里有一个链接解释了如何做到这一点: https ://scotch.io/tutorials/getting-started-with-node-express-and-postgres-using - 续集

这是我如何从 android studio ( Kotlin ) 连接到 api 的示例:这是一个简单的登录请求,其中数据库返回一个布尔值(如果用户无法登录,则为 false,如果用户可以登录,则为 true)下图显示API 返回数据(false 或 true),我写了一封电子邮件和一个显然不存在的密码,如果我写了一封电子邮件和数据库中存在的密码,API 将返回 true [API 返回数据] [2 ]

                mQueue = Volley.newRequestQueue(this);
                var url = "https://thisismylink.herokuapp.com" + "/utilizador/login/" + email + "/" + password
                val request = JsonArrayRequest(Request.Method.GET, url, null, Response.Listener { response ->
                    try {

                        var jsonArray = JSONArray()
                        jsonArray = response.getJSONArray(0)
                        for (i in 0 until jsonArray.length()) {
                            val jsonObject: JSONObject? = jsonArray.getJSONObject(i)
                            //val user = jsonArray.getJSONObject(i)
                            //val bool = jsonObject.getBoolean("login")
                            val boo: Boolean = jsonObject!!.getBoolean("login")

                            if (boo == false) {
                                Toast.makeText(this, "Credenciais Inválidas", Toast.LENGTH_SHORT).show();
                                dialog.hide()
                            } else if (boo == true) {
                                //Toast.makeText(this, email, Toast.LENGTH_SHORT).show();
                                //Toast.makeText(this, password, Toast.LENGTH_SHORT).show();
                                val intent = Intent(this, Home::class.java)
                                startActivity(intent)
                                finish()
                            }
                        }
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }, Response.ErrorListener { error -> error.printStackTrace() })
                mQueue?.add(request)```


Edit: I also used heroku that hosts databases and entire sites [https://www.heroku.com/][3]


  [1]: https://i.stack.imgur.com/1V9WR.png
  [2]: https://i.stack.imgur.com/p5S3f.png
  [3]: https://www.heroku.com/

推荐阅读