首先导入jar包
测试使用的数据表
表名account,表属性:
测试之前准备工作,封装一个JDBC工具类,用来获取连接对象和关闭资源
import java.sql.*;
/**
* @author: changqing
* @date: 2021/3/6 13:43
*/
public final class JDBCUtil {
private JDBCUtil() {
}
private static final String url = "jdbc:mysql://localhost:3306/jdbctest";
private static final String user = "root";
private static final String password = "123456";
//注册驱动
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据连接对象
* @return 数据库连接对象
*/
public static Connection getConnection(){
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void closeAll(ResultSet set, Statement statement,Connection connection){
if (set != null){
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
开始测试
import org.util.JDBCUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 测试jdbc事务
* @author: changqing
* @date: 2021/3/6 16:49
*/
public class Demo04 {
public static void main(String[] args) throws SQLException {
//获取连接对象
Connection connection = JDBCUtil.getConnection();
//关闭事务自动提交,只对当前连接对象有效
connection.setAutoCommit(false);
//操作account表中两条数据一个加余额,一个减余额
//减余额
//获取语句执行者
PreparedStatement preparedStatement =
connection.prepareStatement("update account set money = money -? where name = ? and password = ?");
//设置占位符的值
preparedStatement.setDouble(1,500.0);
preparedStatement.setString(2,"zs");
preparedStatement.setString(3,"123");
//执行sql语句
int result1 = preparedStatement.executeUpdate();
System.out.println(result1);
//模拟异常
//int i = 1/0;
//加余额
PreparedStatement preparedStatement1 =
connection.prepareStatement("update account set money = money + ? where name = ?");
preparedStatement1.setDouble(1,500.0);
preparedStatement1.setString(2,"ls");
// preparedStatement.setString(3,"456");
int result2 = preparedStatement1.executeUpdate();
System.out.println(result2);
//提交事务
connection.commit();
}
}