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 'Öйú±ê׼ʱ¼ä' 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

就一直打印这几句话。

这里的“数据库连接成功"没有打印。

仔细看有这句话:

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";

​

再连接:

成功了。

这里尝试一下不用开辟线程的方法,因为这里没有在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”的问题-优快云博客

然后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-优快云博客

同时更改

Class.forName("com.mysql.jdbc.Driver");

libs中之前的8.*的jar包要删掉,不然会报错。

Android Studio连接MySQL数据库通常需要通过 JDBC (Java Database Connectivity) 来实现。以下是简单的步骤: 1. **添加JDBC驱动**: - 首先,你需要在项目中添加MySQL的JDBC驱动。如果你的项目依赖管理是Gradle,可以在`build.gradle`文件中添加依赖,例如对于Maven库: ``` implementation 'com.mysql:cj.jdbc:8.0.25' ``` - 或者如果你使用的是本地库,下载对应版本的JAR包并将其添加到项目的libs目录下。 2. **配置连接信息**: - 创建一个`DataSource`对象,并提供数据库URL、用户名、密码等信息: ```java String url = "jdbc:mysql://localhost:3306/your_database_name"; String username = "your_username"; String password = "your_password"; Connection conn = DriverManager.getConnection(url, username, password); ``` 3. **处理事务和关闭连接**: - 使用try-with-resources语句自动关闭数据库连接,当代码块结束后会自动关闭Connection: ```java try (Connection conn = DriverManager.getConnection(url, username, password)) { // 执行SQL操作... } catch (SQLException e) { e.printStackTrace(); } ``` 4. **执行SQL操作**: - 使用PreparedStatement防止SQL注入攻击,执行查询或更新操作: ```java String sql = "SELECT * FROM your_table"; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); ``` 5. **读取结果集**: - 循环遍历ResultSet获取数据。 6. **异常处理**: - 编写适当的错误处理代码,如捕获SQLException及其子类。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值