王海鱼 发表于 2024-6-15 02:29:08

Android Studio毗连MYSQL数据库

首先导入mysql的jar包,这里毗连的是8版本的。
https://img-blog.csdnimg.cn/direct/3e751bdaa492473aa30deb0b77c14704.png
这里之前到假如mysql的jar包了
https://img-blog.csdnimg.cn/direct/daf8d020b3994ff8b3e8c1a0393759f0.png
首先跳到Project模式:
https://img-blog.csdnimg.cn/direct/9cf5b5e042c4418d91e9edb36b88e69f.png

直接复制粘贴到这里:
https://img-blog.csdnimg.cn/direct/2cdb029cee944d93b1455dca36ec7ada.png
这里之前到假如了。想删掉重新导入一次,但是报错,什么ioexception。这里将Project Structure中的Moudle中的app中的引入的该jar包的依赖删撤除,然后重启as,再删除就可以了。好吧,这也不是重点。
好,这里重新导入一边,复制jar包,粘贴到libs
https://img-blog.csdnimg.cn/direct/8a952258a7d0448bbe08675ffd9a342f.png
点击ok后:
https://img-blog.csdnimg.cn/direct/9538c15b98354ea9aa35c8dd595b463a.png
这里还没有引入依赖,接下来引入依赖。
有两种方法:
(1)右键jar包
https://img-blog.csdnimg.cn/direct/0ce07b9517a14c34831a1dd5180a00ba.png、
点击这个。之后出现:
https://img-blog.csdnimg.cn/direct/6daccc73352c47849937831910aef43a.png
点击ok,就可以直接在app的build.gradle中创建dependency。
(2)这个比力麻烦
首先进入project structure
快捷键ctrl+alt+shift+s.进入这个界面:
https://img-blog.csdnimg.cn/direct/4d33cb95f9384b2b8027738d8c23ffa2.png
依次点击:
https://img-blog.csdnimg.cn/direct/a4f03a61e11149789fb2c2097c793251.png
点击第二个jar dependency
https://img-blog.csdnimg.cn/direct/95f56122df8544eeb30ed2a213e47a7e.png
出现这个界面:
https://img-blog.csdnimg.cn/direct/9a20b7362bd9416e860d6e559393b028.png
输入如下路径,这里是相对app文件夹的相对路径:
https://img-blog.csdnimg.cn/direct/e1566d378f5e4110a119859e9103fe87.png
https://img-blog.csdnimg.cn/direct/aeb308b1d4fd497b89d734dac1fef06a.png
添加进来了:点击ok
https://img-blog.csdnimg.cn/direct/b17fb3e370444482b3383816cd202033.png
前面 出现‘>' ,引入成功。
https://img-blog.csdnimg.cn/direct/e5616ba9ec2247a4aa5a64d4b59d8d47.png
app的build.gradle中也会自动引入依赖。
https://img-blog.csdnimg.cn/direct/99bc0667cc574858b54b0e0e08bcbc6c.png
到这里mysql的jar包就导入完成了。、
之后再步伐中可以通过:
Class.forName("com.mysql.cj.jdbc.Driver"); 来引入。

接下来就可以创建数据库毗连了。
这里写了一个工具类,将毗连mysql的过程封装起来,直接再main函数中调用即可。这里main函数好像可以不new对象就调用对象中的static方法。
https://img-blog.csdnimg.cn/direct/c14aefa09a2248cd8c00f67d51143e6b.png
用到的就这两个,此中connection是工具类,main调用工具类。
connection的代码如下:
package com.example.myapplication;

import android.util.Log;

import java.sql.DriverManager;
import java.sql.SQLException;


public class Connection {

public static void mymysql(){
      final Thread thread =new Thread(new Runnable() {
            @Override
            public void run() {

                while (!Thread.interrupted()) {
                  try {
                        Thread.sleep(100);// 每隔0.1秒尝试连接
                  } catch (InterruptedException e) {
//                        Log.e(TAG, e.toString());
                        System.out.println(e.toString());
                  }

// 1.加载JDBC驱动
                  try {
                        Class.forName("com.mysql.cj.jdbc.Driver");
//                        Log.v(TAG, "加载JDBC驱动成功");
                        System.out.println("加载JDBC驱动成功");
                  } catch (ClassNotFoundException e) {
//                        Log.e(TAG, "加载JDBC驱动失败");
                        System.out.println("加载JDBC驱动失败");
                        return;
                  }

                  // 2.设置好IP/端口/数据库名/用户名/密码等必要的连接信息
                  String ip = "";
                  int port = 3306;
                  String dbName = "";
                  String url = "jdbc:mysql://" + ip + ":" + port
                            + "/" + dbName+"?useUnicode=true&characterEncoding=utf-8&useSSL=false";

//                  useUnicode=true&characterEncodeing=UTF-8&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true"

                  // 构建连接mysql的字符串
                  String user = "root";
                  String password = "WQT200126";

                  // 3.连接JDBC
                  try {
                        System.out.println("111");

                        java.sql.Connection conn = DriverManager.getConnection(url, user, password);
//                        Log.d(TAG, "数据库连接成功");
                        System.out.println("数据库连接成功");
                        conn.close();
                        return;
                  }
                  catch (SQLException e) {
//                        Log.e(TAG, e.getMessage());
                        System.out.println('H'+e.getMessage());
                  }

                }
            }
      });
      thread.start();



    }
} 此中数据库设置的代码是这些:

String ip = "";
            int port = 3306;
            String dbName = "";
            String url = "jdbc:mysql://" + ip + ":" + port
                  + "/" + dbName+"?useUnicode=true&characterEncoding=utf-8&useSSL=false";

//                  useUnicode=true&characterEncodeing=UTF-8&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true"

​ 此中,dbname就是毗连的数据库名称,假如是毗连本机,ip地点就是127.0.0.1。
还必要加上用户名和密码:

String user = "root";
            String password = "";

​ 设置好后就通过:
java.sql.Connection conn = DriverManager.getConnection(url, user, password); 来毗连。
这里as中好像不答应耗时步伐再主线程中,意思是毗连MYSQL是个耗时步伐,所以必要别的开辟一个线程来毗连MYSQL。所以这里new了一个Thread。
然后工具类写好了,接下来再main函数中引入。
main函数代码如下:
package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

//import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.example.myapplication.Connection;

public class Main {
    public static void main(String[] args) {
      System.out.println("eh");
      Connection.mysql1();

}
} 接下来运行main函数。再运行前,要调解这里:
https://img-blog.csdnimg.cn/direct/716515c5b32f46e694b0c1187c438f6b.png
然后运行:
运行结果:
HThe server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
加载JDBC驱动成功
111
HThe server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
加载JDBC驱动成功
111
HThe server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
加载JDBC驱动成功
111 就不绝打印这几句话。
https://img-blog.csdnimg.cn/direct/673df5c0588842f08792fed97d9a5c1e.png
这里的“数据库毗连成功"没有打印。
细致看有这句话:
HThe server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. 好像要加什么时间域。
改了url
原来的url是:
String url = "jdbc:mysql://" + ip + ":" + port
                            + "/" + dbName+"?useUnicode=true&characterEncoding=utf-8&useSSL=false"; 改为:

String url = "jdbc:mysql://" + ip + ":" + port
                            + "/" + dbName+"? useUnicode=true&characterEncodeing=UTF-8&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true";

​ 再毗连:
https://img-blog.csdnimg.cn/direct/877d55d37ddd4148853cf5b087e5534d.png
成功了。
这里尝试一下不用开辟线程的方法,因为这里没有在app上运行:
代码:
工具类中加入:

public static void mysql1(){
      String success = "111";
      System.out.println(success);
//      while (this.success_con!="111") {
      while (success=="111"){

// 1.加载JDBC驱动
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
//                        Log.v(TAG, "加载JDBC驱动成功");
                System.out.println("加载JDBC驱动成功");
            } catch (ClassNotFoundException e) {
//                        Log.e(TAG, "加载JDBC驱动失败");
                System.out.println("加载JDBC驱动失败");
                return;
            }

            // 2.设置好IP/端口/数据库名/用户名/密码等必要的连接信息
            String ip = "127.0.0.1";
            int port = 3306;
            String dbName = "mm";
            String url = "jdbc:mysql://" + ip + ":" + port
                  + "/" + dbName+"?useUnicode=true&characterEncoding=utf-8&useSSL=false";

//                  useUnicode=true&characterEncodeing=UTF-8&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true"

            // 构建连接mysql的字符串
            String user = "root";
            String password = "WQT200126";

            // 3.连接JDBC
            try {
                System.out.println("111");

                java.sql.Connection conn = DriverManager.getConnection(url, user, password);
//                        Log.d(TAG, "数据库连接成功");
                System.out.println("数据库连接成功");
                success = "sss";
                conn.close();
                return;
            }
            catch (SQLException e) {
//                        Log.e(TAG, e.getMessage());
                System.out.println('H'+e.getMessage());
            }

      }

    }

​ main函数中:
public class Main {
    public static void main(String[] args) {
      System.out.println("eh");
      Connection.mysql1();
//      this.test();
//      Main main = new Main();
//      main.test();
    }
} 结果:
https://img-blog.csdnimg.cn/direct/9fd89378914e4903be83ffaf07915035.png
也可以毗连。

接下来试一下在app中运行。
这里必要注意的是,在app中运行要开辟线程。不在app中运行,也就是不在oncreate,onclick中打印信息,不能用Log()。
之前的代码中,我都是将log注释掉了,用的sout。
首先在main函数中添加oncreate方法。
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Connection.mymysql1();
    } 必要注意的是:
https://img-blog.csdnimg.cn/direct/473234bcd2d04836953c2d8d5da12649.png
https://img-blog.csdnimg.cn/direct/cec27a44ae5840158056fbc43881675d.png
运行前要sync:同步一下。
https://img-blog.csdnimg.cn/direct/062830b722d84b54b1161f11b4d4c058.png
同步完成:
https://img-blog.csdnimg.cn/direct/9031ec92e10e47fdba6b5454417a4f2b.png
点击这个运行:
https://img-blog.csdnimg.cn/direct/39711f1f5e864c5996c927d17b4efab8.png
运行会报错:
Cannot fit requested classes in a single dex file (# methods: 81010 > 65536) 好像是容量超过限制。
参考这篇:解决“Cannot fit requested classes in a single dex file”的问题-CSDN博客
然后SYNC,BUILD,RUN
成功。

然后尝试在手机上运行。
在main中加入代码:
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Connection.mymysql1();
    } https://img-blog.csdnimg.cn/direct/351ca3ef91914a2ca8050ab7825b19ac.png
运行成功。
必要注意,这里mysql的jar包要换位5.*,否则在手机上运行会报错。
参考这篇:安卓毗连云mysql时报错:java.lang.NoClassDefFoundError: Failed resolution of: Ljava/sql/SQLType-CSDN博客
同时更改
Class.forName("com.mysql.jdbc.Driver"); libs中之前的8.*的jar包要删掉,否则会报错。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Android Studio毗连MYSQL数据库