描述: 编写一个Java程序,使用JDBC连接到MySQL数据库。
要求:
1、使用DriverManager和Connection接口。
2、输出一条消息表明是否成功连接到数据库。
描述: 编写一个Java程序,从数据库中查询所有用户的信息,并打印出来。
要求:
1、使用Statement对象执行SQL查询。
2、使用ResultSet遍历结果集并打印每个用户的姓名和电子邮件。
3、处理可能出现的异常。
描述: 编写一个Java程序,向用户表中插入新的用户记录。
要求:
1、使用PreparedStatement以防止SQL注入。
2、插入至少两条记录,每条记录包含姓名、电子邮件和密码。
3、检查插入是否成功,并输出相应的信息。
描述: 编写一个Java程序,更新用户表中的某个用户信息,然后删除该用户。
要求:
1、使用PreparedStatement进行更新操作。
2、使用PreparedStatement进行删除操作。
3、验证更新和删除是否成功。
4、处理可能出现的异常。
描述: 编写一个Java程序,批量更新多个用户的信息。
要求:
1、使用PreparedStatement添加批处理命令。
2、执行批处理更新。
3、检查更新是否成功,并输出相应的信息。
4、处理可能出现的异常。
## 事务管理 (20 分)
描述: 编写一个Java程序,演示如何在JDBC中使用事务管理。
要求:
1、在一个事务中执行多个更新操作(如插入两条记录)。
2、如果其中一个更新失败,确保整个事务回滚。
package com.bwie;
import org.junit.jupiter.api.Test;
import java.sql.*;
import java.util.Arrays;
/**
* @author 军哥
* @version 1.0
* @description: TODO
* @date 2025/6/21 11:07
*/
public class TestDbApp {
@Test
public void testGetVersion() {
String url = "jdbc:mysql://192.168.80.192:3306/db_2212a_shop?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = "root";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
DatabaseMetaData metaData = conn.getMetaData();
System.out.println("JDBC驱动名称: " + metaData.getDriverName());
System.out.println("JDBC驱动版本: " + metaData.getDriverVersion());
System.out.println("JDBC主版本号: " + metaData.getDriverMajorVersion());
System.out.println("JDBC次版本号: " + metaData.getDriverMinorVersion());
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* @description 测试链接数据库
* @params []
* @return void
* @author 军哥
* @date 2025/6/21 11:07
*/
@Test
public void testConnectDB() {
String url = "jdbc:mysql://192.168.80.192:3306/db_2212a_shop?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = "root";
try {
Connection connection = DriverManager.getConnection(url, user, password);
if(connection == null) {
System.out.println("数据库连接失败");
}
else {
System.out.println("数据库连接成功");
//¢使用Statement对象执行SQL查询。
//¢使用ResultSet遍历结果集并打印每个用户的姓名和电子邮件。
Statement statement = connection.createStatement();
String sql = "SELECT * FROM tb_user";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()) {
String userName = resultSet.getString("user_name");
String userEmail = resultSet.getString("user_email");
System.out.println("用户名:" + userName + ",邮箱:" + userEmail);
}
// 关闭数据库连接
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Test
public void testInsertUser() {
String url = "jdbc:mysql://192.168.80.192:3306/db_2212a_shop?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = "root";
try {
Connection connection = DriverManager.getConnection(url, user, password);
if(connection == null) {
System.out.println("数据库连接失败");
}
else {
System.out.println("数据库连接成功");
//¢使用PreparedStatement以防止SQL注入。
//¢插入至少两条记录,每条记录包含姓名、电子邮件和密码。
//¢检查插入是否成功,并输出相应的信息。
String[][] userList = {
{"张三", "zhangsan@example.com"},
{"李四", "lisi@example.com"}
};
String sql = "insert into tb_user(user_name,user_email) value(?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (String[] strings : userList) {
preparedStatement.setString(1, strings[0]);
preparedStatement.setString(2, strings[1]);
int iRow = preparedStatement.executeUpdate();
if(iRow > 0) {
System.out.println("插入成功");
}
else {
System.out.println("插入失败");
}
}
// 关闭数据库连接
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
// ¢使用PreparedStatement进行更新操作。
//¢使用PreparedStatement进行删除操作。
//¢验证更新和删除是否成功。
//¢处理可能出现的异常。
@Test
public void testUpdateAndDelete() {
String url = "jdbc:mysql://192.168.80.192:3306/db_2212a_shop?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = "root";
try {
Connection connection = DriverManager.getConnection(url, user, password);
if(connection == null) {
System.out.println("数据库连接失败");
}
else {
System.out.println("数据库连接成功");
// ¢使用PreparedStatement进行更新操作。
String sql = "update tb_user set user_email = ? where user_name = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "123@qq.com");
preparedStatement.setString(2, "张三");
int iRow = preparedStatement.executeUpdate();
if(iRow >= 0) {
System.out.println("更新成功");
}
else {
System.out.println("更新失败");
}
// ¢使用PreparedStatement进行删除操作。
sql = "delete from tb_user where user_name = ?";
PreparedStatement preparedStatement1 = connection.prepareStatement(sql);
preparedStatement1.setString(1, "张三");
System.out.println(preparedStatement1.toString());
// executeUpdate 这个函数不能携带SQL字符串
iRow = preparedStatement1.executeUpdate();
if(iRow >= 0) {
System.out.println("删除成功");
}
else {
System.out.println("删除失败");
}
// 关闭数据库连接
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Test
public void testBatchUpdate() {
String url = "jdbc:mysql://192.168.80.192:3306/db_2212a_shop?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = "root";
try {
Connection connection = DriverManager.getConnection(url, user, password);
if(connection == null) {
System.out.println("数据库连接失败");
}
else {
System.out.println("数据库连接成功");
//¢使用PreparedStatement添加批处理命令。
//¢执行批处理更新。
//¢检查更新是否成功,并输出相应的信息。
//¢处理可能出现的异常。
String sql = "update tb_user set create_time=? where user_id=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 关闭自动提交
connection.setAutoCommit(false);
// 添加批处理命令
preparedStatement.setDate(1, new Date(System.currentTimeMillis()));
preparedStatement.setInt(2, 1);
preparedStatement.addBatch();
preparedStatement.setDate(1, new Date(System.currentTimeMillis()));
preparedStatement.setInt(2, 2);
preparedStatement.addBatch();
preparedStatement.setDate(1, new Date(System.currentTimeMillis()));
preparedStatement.setInt(2, 3);
preparedStatement.addBatch();
// 批量更新
int[] ints = preparedStatement.executeBatch();
System.out.println("更新了" + ints.toString());
// 提交更新
connection.commit();
// 关闭数据库连接
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Test
public void testBatchInsert() {
String url = "jdbc:mysql://192.168.80.192:3306/db_2212a_shop?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = "root";
try {
Connection connection = DriverManager.getConnection(url, user, password);
if(connection == null) {
System.out.println("数据库连接失败");
}
else {
System.out.println("数据库连接成功");
//¢在一个事务中执行多个更新操作(如插入两条记录)。
//¢如果其中一个更新失败,确保整个事务回滚。
try {
String sql = "insert into tb_user(user_name, user_pass) value(?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 开启事务
connection.setAutoCommit(false);
// 添加批处理命令
preparedStatement.setString(1, "张三1");
preparedStatement.setString(2, "123456");
preparedStatement.addBatch();
preparedStatement.setString(1, "李四1");
preparedStatement.setString(2, "123456");
preparedStatement.addBatch();
int[] ints = preparedStatement.executeBatch();
if(ints.length > 0) {
Arrays.stream(ints).forEach(System.out::println);
}
if(true) {
throw new SQLException();
}
// 提交事务
connection.commit();
} catch (SQLException e) {
//throw new RuntimeException(e);
System.out.println("事务回滚~~~~~~~~~~~~~~~~");
// 如果发生错误,进行事务回滚
connection.rollback();
}
// 关闭数据库连接
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Test
public void insert(){
String url= "jdbc:mysql://192.168.80.192:3306/db_2212a_shop?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8";
String username= "root";
String password= "root";
try {
Connection connection = DriverManager.getConnection(url, username, password);
if(connection==null){
System.out.println("数据库连接失败");
}else{
System.out.println("数据库连接成功");
String sql="insert into tb_user(user_name,create_by) value(?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"张三");
preparedStatement.setString(2,"李四");
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("新增成功");
}else{
System.out.println("新增失败");
}
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}