java 如何使 MySQL Connector/J 在 android 上工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25044910/
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-11-02 07:12:29  来源:igfitidea点击:

How to make MySQL Connector/J working on android?

javaandroidmysql

提问by gotgot1995

I've got a MySQL server running on a local Linux machine. I haven't been faced to any problems communicating with it and executing SQL statements through a simple Java program (running inside of eclipse) using the MySQL Connector/J. Here is my simple Java program:

我有一个在本地 Linux 机器上运行的 MySQL 服务器。我在使用 MySQL Connector/J 通过一个简单的 Java 程序(在 eclipse 中运行)与它进行通信和执行 SQL 语句时没有遇到任何问题。这是我的简单 Java 程序:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.lang.*;


public class main{
    private static void request(){
        String url = "jdbc:mysql://myadress:3306/mydatabase";
        String user = "user";
        String passwd = "passwd";

        Connection conn = null;
        try{
            /* Initializing the connection */
            conn = DriverManager.getConnection(url, user, passwd);

            Statement statement = conn.createStatement();

            ResultSet resultset = statement.executeQuery(/* MY SQL reqquest */);

            while(resultset.next()){
                System.out.println(resultset.getString(/* THE COLUMN AND ROW I WANTED IN MY REQUEST */));       
            }

        }catch(SQLException e){
            System.out.println("SQL connection error: " + e.getMessage());
        }finally {
            if(conn != null){
                try{
                    /* CLosing connection */
                    conn.close();
                }catch (SQLException e){
                    System.out.println("Error while closing the connection: " + e.getMessage());
                }
            }
        }
    }
    public static void main(String[] args) {
        try{ // Loading the MySQL Connector/J driver
            Class.forName("com.mysql.jdbc.Driver");
        }catch(ClassNotFoundException e){
            System.out.println("Error while loading the Driver: " + e.getMessage());
        }
        request();
    }

}

This code works perfectly inside of eclipse and can perform as much SELECT as UPDATE SQL requests without any problem. When I tried to adapt this request method to my MainActivity.java class, my android application does load the driver correctly but can't communicate with my MySQL server and returns me an error.

这段代码在 eclipse 中完美运行,并且可以毫无问题地执行与 UPDATE SQL 请求一样多的 SELECT。当我尝试将此请求方法应用于我的 MainActivity.java 类时,我的 android 应用程序确实正确加载了驱动程序,但无法与我的 MySQL 服务器通信并返回一个错误。

If I enter a local IP adress to my server in the previous code and connect my android phone to the Wi-Fi, then my app returns me:

如果我在前面的代码中输入一个本地 IP 地址到我的服务器并将我的 android 手机连接到 Wi-Fi,那么我的应用程序会返回我:

"Communication link failure. The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."

“通信链路故障。上一次成功发送到服务器的数据包是 0 毫秒前。驱动程序没有收到来自服务器的任何数据包。”

But if I try to enter an external IP adress to my server in the same previous code (don't worry the MySQL port is open to the internet and my server is listening to any IP), use my android phone over an LTE internet connection, I get a different error:

但是,如果我尝试在相同的先前代码中向我的服务器输入外部 IP 地址(不要担心 MySQL 端口对互联网开放并且我的服务器正在侦听任何 IP),请通过 LTE 互联网连接使用我的 android 手机,我得到一个不同的错误:

"Could not create connection to database server"

“无法创建与数据库服务器的连接”

Up until now, none of my research has helped me out. Does anyone has any idea of where my problem could come from ? Thanks in advance :)

直到现在,我的研究都没有帮助我。有没有人知道我的问题可能来自哪里?提前致谢 :)

采纳答案by Oleg Gryb

The general misconception among Java developers who is moving to Android world is that everything that has been created for old good Java can be used on Android as well. Since Android usage of Java has violated the major Java principle, "write once, run everywhere", it's simply not true. I've seen people trying to use common Apache jars with Android, which resulted to weird errors (see Can't import Apache HTTP in Eclipse).

转向 Android 世界的 Java 开发人员普遍存在的误解是,为旧的优秀 Java 创建的所有内容也可以在 Android 上使用。由于 Android 对 Java 的使用违反了主要的 Java 原则,“一次编写,到处运行”,这根本不是真的。我见过有人试图在 Android 中使用常见的 Apache jar,这导致了奇怪的错误(请参阅无法在 Eclipse 中导入 Apache HTTP)。

The same problems seem to be true for Java JDBC drivers and API's, e.g. see answers here: Connecting to MySQL from Android with JDBC

Java JDBC 驱动程序和 API 似乎也存在同样的问题,例如,请参阅此处的答案:Connecting to MySQL from Android with JDBC

The common advice - each time when you try to use a 3rd party JAR with Android, check if it's compatible with the latter or if there is a port, which is specific for Android.

常见建议 - 每次尝试在 Android 上使用 3rd 方 JAR 时,请检查它是否与后者兼容,或者是否有特定于 Android 的端口。

回答by Matvi

It is possible, if you use the correct connector. I use the connector 3.0.17, in some others examples the connector is mysql-connector-java-5.1.24-bin.jar

如果您使用正确的连接器,这是可能的。我使用连接器 3.0.17,在其他一些示例中,连接器是 mysql-connector-java-5.1.24-bin.jar

  1. Just download the right connector.
  2. Past the connector-java.x.x.x-bin.jar on libs
  3. Import the java.sql

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    

    Use the next method to connect

    public void conectarBDMySQL (String user, String password, 
                String ip, String port, String cat)
        {
            if (conexionMySQL == null)      
            {
                String urlConexionMySQL = "";
                if (cat!= "")
                    urlConexionMySQL = "jdbc:mysql://" + ip + ":" + port+ "/" + cat;
                else
                    urlConexionMySQL = "jdbc:mysql://" + ip + ":" + port;
                if (user!= "" & password!= "" & ip != "" & port!= "")
                {
                    try 
                    {
                        Class.forName("com.mysql.jdbc.Driver");
                        conexionMySQL = DriverManager.getConnection(urlConexionMySQL, 
                                user, password);                    
                    } 
                    catch (ClassNotFoundException e) 
                    {
                          Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                    } 
                    catch (SQLException e) 
                    {
                          Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    
  1. 只需下载正确的连接器。
  2. 过去 libs 上的 connector-java.xxx-bin.jar
  3. 导入 java.sql

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    

    使用下一个方法连接

    public void conectarBDMySQL (String user, String password, 
                String ip, String port, String cat)
        {
            if (conexionMySQL == null)      
            {
                String urlConexionMySQL = "";
                if (cat!= "")
                    urlConexionMySQL = "jdbc:mysql://" + ip + ":" + port+ "/" + cat;
                else
                    urlConexionMySQL = "jdbc:mysql://" + ip + ":" + port;
                if (user!= "" & password!= "" & ip != "" & port!= "")
                {
                    try 
                    {
                        Class.forName("com.mysql.jdbc.Driver");
                        conexionMySQL = DriverManager.getConnection(urlConexionMySQL, 
                                user, password);                    
                    } 
                    catch (ClassNotFoundException e) 
                    {
                          Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                    } 
                    catch (SQLException e) 
                    {
                          Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    

It works perfect for me, and i have had no problems!!!

它非常适合我,我没有遇到任何问题!!!

回答by Boardy

Generally, the recommended approach is to post to a web service, and allow the web service to perform the required actions on the database. However, there is an open source library on GitHubwhich allows you to connect directly to the database server without the need of a web service.

通常,推荐的方法是发布到 Web 服务,并允许 Web 服务对数据库执行所需的操作。但是,GitHub 上有一个开源库,它允许您直接连接到数据库服务器,而无需 Web 服务。

The library is fairly new and has been tested against MySQL 5.1 -> 5.7 which should also be compatible with the equivalent MySQL version to MariaDB.

该库是相当新的,并且已经针对 MySQL 5.1 -> 5.7 进行了测试,这也应该与 MariaDB 的等效 MySQL 版本兼容。

Disclaimer: I wrote it.

免责声明:我写的。