Android Studio连接MYSQL数据库
首先导入mysql的jar包,这里连接的是8版本的。

这里之前到如果mysql的jar包了

首先跳到Project模式:
直接复制粘贴到这里:

这里之前到如果了。想删掉重新导入一次,但是报错,什么ioexception。这里将Project Structure中的Moudle中的app中的引入的该jar包的依赖删除掉,然后重启as,再删除就可以了。好吧,这也不是重点。
好,这里重新导入一边,复制jar包,粘贴到libs

点击ok后:

这里还没有引入依赖,接下来引入依赖。
有两种方法:
(1)右键jar包
 、
、
点击这个。之后出现:

点击ok,就可以直接在app的build.gradle中创建dependency。
(2)这个比较麻烦
首先进入project structure
快捷键ctrl+alt+shift+s.进入这个界面:

依次点击:

点击第二个jar dependency

出现这个界面:

输入如下路径,这里是相对app文件夹的相对路径:


添加进来了:点击ok

前面 出现‘>' ,引入成功。

app的build.gradle中也会自动引入依赖。

到这里mysql的jar包就导入完成了。、
之后再程序中可以通过:
Class.forName("com.mysql.cj.jdbc.Driver");来引入。
接下来就可以建立数据库连接了。
这里写了一个工具类,将连接mysql的过程封装起来,直接再main函数中调用即可。这里main函数好像可以不new对象就调用对象中的static方法。

用到的就这两个,其中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函数。再运行前,要调整这里:

然后运行:
运行结果:
HThe server time zone value '?D1ú±ê×?ê±??' 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 '?D1ú±ê×?ê±??' 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 '?D1ú±ê×?ê±??' 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 '?D1ú±ê×?ê±??' 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";
?再连接:

成功了。
这里尝试一下不用开辟线程的方法,因为这里没有在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();
    }
}结果:

也可以连接。
接下来试一下在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();
    }需要注意的是:


运行前要sync:同步一下。

同步完成:

点击这个运行:

运行会报错:
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();
    }
运行成功。
需要注意,这里mysql的jar包要换位5.*,不然在手机上运行会报错。
参考这篇:安卓连接云mysql时报错:java.lang.NoClassDefFoundError: Failed resolution of: Ljava/sql/SQLType-CSDN博客
同时更改
Class.forName("com.mysql.jdbc.Driver"); 
libs中之前的8.*的jar包要删掉,不然会报错。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!