Android Studio 项目与 MySQL 数据库的连接

Connection of Android Studio project to MySQL database

我正在开发一个 android 工作室项目,并希望能够从我正在编程的电脑上的数据库访问数据。我想使用 MySQL 数据库,因为我之前曾与他们合作过。我想知道是否可以从 android 工作室完成。如果可能的话,代码对我来说是什么?我查看了其他人的问题和答案,所有这些问题和答案都对我产生了错误。 提前致谢

我已尝试以下操作,我的所有 ip、端口、用户名和密码信息都是正确的,但我一直收到以下错误:E/Error 连接:com.mysql.jdbc.Driver 声明我的属性后,我的连接 class 中的代码如下


        //declaring connection policy
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
        StrictMode.setThreadPolicy(policy);
        Connection connection = null;
        String ConnectionURL = null;

        //starts actual connection to db
        try
        {
            //establishing connection to Database
            //all hard coded
            Class.forName("com.mysql.jdbc.Driver");
            ConnectionURL= "jdbc:jtds:sqlserver://"+ ip + ":"+ port+";"+ "databasename="+ database+";user="+uname+";password="+pass+";";
            connection = DriverManager.getConnection(ConnectionURL);
        }
        //Catches any error in the data
        catch (Exception e)
        {
            //executes if there is a error connecting to the database
            Log.e("Error in connection", e.getMessage());
            System.out.println("Error connecting to db");
        }
        //returns the connection to the main class
        //it will then be sent to the DBmanager class and used to get the data out of the database
        return connection;
    }
}

不鼓励将应用程序直接连接到 mysql 服务器(以及其他 rdms),因为您需要这样做才能通过直接访问将数据库打开到互联网,这是致命的安全风险。

搜索

  • 休息 API MySQL android

你会发现很多教程

喜欢这个短片https://phppot.com/php/php-mysql-rest-api-for-android/ or this https://www.javahelps.com/2018/12/access-mysql-from-android-through.html

Android Studio 将难以连接到 mySQL 数据库。对于此用例,在机器本身上存储 sqlite 数据库通常更容易。