Android 操控 mysql增删改查_Android 连接 MySQL 并进行基本的增删改查操作

本文介绍了Android应用如何连接到本地MySQL数据库进行增删改查操作。首先,需要导入mysql-connector-java的jar包,并配置兼容性选项。接着,在AndroidManifest.xml中添加网络权限。在数据库中创建表,然后通过DbOpenHelper工具类实现数据库连接,包括获取Connection、关闭Connection的方法。此外,还提供了插入、更新、删除和查询数据的示例代码,并记录了在连接过程中可能遇到的问题及其解决方案。
摘要由CSDN通过智能技术生成

准备工作

导入 jar 包

下载 mysql-connector-java 包(吃过亏的表示推荐 5.x.x 版本,8.x.x 版本会出现挺多问题的):mysql-connector-java 下载地址

打开 AS,将 jar 包复制到 libs 文件夹下, 复制完后右键 jar 包,点击 “add as library”,将 jar 包导入相应 module

如果导入的 mysql-connector-java 版本为 8.x.x,则需要在 app\build.gradle 中添加:

android {

// ...

compileOptions {

sourceCompatibility 1.8

targetCompatibility 1.8

}

}

添加网络权限

在 AndroidManifest.xml 中添加:

在本地主机的 mysql 中创建要连接的数据库

使用命令行创建数据库

create database ;

使用 navicat 等可视化工具直接创建数据库

连接 MySql

直接上工具类:

/**

* @author Feng Zhaohao

* Created on 2019/11/24

*/

public class DbOpenHelper {

private static String driver = "com.mysql.jdbc.Driver";// mysql 驱动

private static String ip = "xxx.xxx.xxx.xxx"; // 安装了 mysql 的电脑的 ip 地址

private static String dbName = "TestDB"; // 要连接的数据库

private static String url = "jdbc:mysql://" + ip + ":3306/" + dbName

+ "?useUnicode=true&characterEncoding=utf8"; // mysql 数据库连接 url

private static String user = "root"; // 用户名

private static String password = "xxxxxx"; // 密码

private static Connection sConnection;

/**

* 连接数据库

*/

public static Connection getConnection() {

if (sConnection == null) {

try {

Class.forName(driver); // 获取 mysql 驱动

sConnection = DriverManager.getConnection(url, user, password); // 获取连接

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}

}

return sConnection;

}

/**

* 关闭数据库

*/

public static void closeConnection() {

if (sConnection != null) {

try {

sConnection.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

通过 getConnection() 获得连接,不需要连接时记得使用 closeConnection() 关闭。

注意:

url 连接中的 ip 地址是指本地主机(安装了 mysql 的电脑)的 ip 地址,不是 localhost(localhost 是你手机的 ip 地址,你手机不可能装 mysql 吧)

url 连接中的数据库名不要写错,必须是本地主机的 mysql 中已经创建好的数据库

需要在子线程中进行连接 MySQL 操作

连接后进行增删改查

准备工作:在 TestDB 数据库中创建了一个 person 表,该表有 3 个 column: id(int 类型,主键,自增长)、name(text 类型,表示姓名)、age(int 类型,表示年龄)。

注意:连接 MySQL 和对 MySQL 数据库进行增删改查操作都需要放在子线程中进行,不然会抛出异常。

插入数据

/**

* 插入数据(插入一条姓名为 name,年龄为 age 的数据)

*/

public static void insert(String name, int age) {

// 插入数据的 sql 语句

String sql = "insert into person (name, age) values (?, ?)";

Connection connection = DbOpenHelper.getConnection();

PreparedStatement ps = null;

if (connection == null) {

return;

}

try {

ps = connection.prepareStatement(sql);

// 为两个 ? 设置具体的值

ps.setString(1, name);

ps.setInt(2, age);

// 执行语句

ps.executeUpdate();

} catch (SQLException e) {

e.printStackTrace();

} finally {

if (ps != null) {

try {

ps.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

更新数据

/**

* 更新数据(将姓名为 name 的年龄改为 newAge)

*/

public static void update(String name, int newAge) {

// 更新数据的 sql 语句

String sql = "update person set age = ? where name = ?";

Connection connection = DbOpenHelper.getConnection();

PreparedStatement ps = null;

try {

ps = connection.prepareStatement(sql);

// 为两个 ? 设置具体的值

ps.setInt(1, newAge);

ps.setString(2, name);

// 执行语句

ps.executeUpdate();

} catch (SQLException e) {

e.printStackTrace();

} finally {

if (ps != null) {

try {

ps.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

删除数据

/**

* 删除数据(删除姓名为 name 的数据)

*/

public static void delete(String name) {

// 删除数据的 sql 语句

String sql = "delete from person where name = ?";

Connection connection = DbOpenHelper.getConnection();

PreparedStatement ps = null;

try {

ps = connection.prepareStatement(sql);

// 为 ? 设置具体的值

ps.setString(1, name);

// 执行语句

ps.executeUpdate();

} catch (SQLException e) {

e.printStackTrace();

} finally {

if (ps != null) {

try {

ps.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

查询数据

/**

* 查询 person 表的所有数据

*/

public static String query() {

// 查询的 sql 语句

String sql = "select * from person";

Connection connection = DbOpenHelper.getConnection();

PreparedStatement ps = null;

ResultSet rs = null;

StringBuilder builder = new StringBuilder();

try {

ps = connection.prepareStatement(sql);

// 执行语句(执行查询语句用的是 executeQuery 方法)

rs = ps.executeQuery();

// 得到查询结果

if (rs != null) {

while (rs.next()) {

builder.append("[name = ");

builder.append(rs.getString("name"));

builder.append(", age = ");

builder.append(rs.getInt("age"));

builder.append("] ");

}

}

} catch (SQLException e) {

e.printStackTrace();

} finally {

if (ps != null) {

try {

ps.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (rs != null) {

try {

rs.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

return builder.toString();

}

出现的问题

下面是对在连接 MySQL 过程中出现问题的记录,其中问题 2、问题 4、问题 5 是导入 mysql-connector-java-8.x.x 出现的问题;问题 6 是导入 mysql-connector-java-5.x.x 出现的问题。

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

解决:在项目中导入 mysql-connector-java 包

Loading class com.mysql.jdbc.Driver. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver.

解决:将 mysql 驱动由 "com.mysql.jdbc.Driver" 换成 "com.mysql.cj.jdbc.Driver"

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

原因:连接的数据库(在连接 url 中指定的数据库)未创建(很多博客都没有说这点,结果一开始我傻傻地以为随便输入一个数据库名就行)

解决:连接前先在本地创建好需要连接的数据库

java.sql.SQLException: The 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 中添加 serverTimezone,例如 "jdbc:mysql://ip:3306/dbName?serverTimezone=GMT%2B8"

java.lang.ClassNotFoundException: Didn’t find class “java.sql.SQLType” on path: DexPathList…

原因:推测和 jdk1.8 版本有关,但是在 IDEA 上用 Java 连接 MySql 又正常,有点迷

解决:放弃 mysql-connector-java-8.x.x,重新导了个更低版本的 mysql-connector-java-5.x.x(又回到最初的起点...)。

注意,导了 5.x.x 版本后问题 2、问题 4 就不存在了。

Unknown initial character set index ‘255’ received from server. Initial client character

解决: 在连接 url 指定字符集,例如 "jdbc:mysql://ip:3306/dbName?useUnicode=true&characterEncoding=utf8"

参考

Android 连接MySQL数据库并进行增删改查操作

mysql-connector-java与Mysql、Java的对应版本

Unknown initial character set index ‘255’ received from server. Initial client character 解决方法

springboot 连接MySQL的时候报错The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrec

Host is not allowed to connect to this MySQL server解决方法

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值