简体   繁体   English

如何通过Android应用程序与外部SQL数据库进行通信?

[英]How to communicate with an external SQL database through an Android app?

I have an Android app which writes/reads from an external SQL database through a PHP script. 我有一个Android应用程序,可通过PHP脚本从外部SQL数据库写入/读取。 Both the database and the PHP script is hosted on Amazon Web Services (AWS). 数据库和PHP脚本都托管在Amazon Web Services(AWS)上。 The app sends HTTP request to the PHP script, and the PHP script communicates with the database. 该应用程序将HTTP请求发送到PHP脚本,然后PHP脚本与数据库进行通信。

Are there easier ways to connect the app with the database? 是否有更简单的方法将应用程序与数据库连接? I feel like this method is kinda hacky. 我觉得这种方法有点怪异。 Or is this how it is done? 还是这是怎么做的? Is it possible to avoid the PHP script entirely and just communicate with the database through Java in the app? 是否可以完全避免使用PHP脚本,而仅通过应用程序中的Java与数据库进行通信?

Below is the code for fetching everything in the database. 以下是用于获取数据库中所有内容的代码。

The php script: php脚本:

$servername = "";
$username = "";
$password = "";

$conn = mysqli_connect($servername, $username, $password);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
        echo "rowname1: " . $row["rowname1"]. " rowname2: " . $row["rowname2"] . "\n";
    }
} else {
    echo "0 results";
}

$conn->close();

The Java code: Java代码:

requestQueue = Volley.newRequestQueue(this);
    String url = "";
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            textDatabase.setText(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            textDatabase.setText(error.toString());
        }
    });

    requestQueue.add(stringRequest);

This is the correct way to do that, via API. 这是通过API执行此操作的正确方法。

Frontend Application (Android, iOS, browser) <-> API <-> Backend

You can connect direct to the database, but you should not. 您可以直接连接到数据库,但不能。 To be able to do that, you have to put user and password in your application. 为此,您必须在应用程序中输入用户名和密码。 Doing this, how do you prevent users to connect on your database and changing all they want? 这样做,如何防止用户连接数据库并更改他们想要的所有内容? There are many more points against this approach. 还有许多反对这种方法的观点。

Look for REST APIs , or maybe GraphQL . 寻找REST APIsGraphQL

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

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