jdbc实现事务回滚/提交

public class Test {
	public static void main(String[] args) {
		Statement statement = null;
		Connection connection = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "");
			statement = connection.createStatement();
			connection.setAutoCommit(false);//相当于jdbc中的set autocommit = 0;
			statement.addBatch("update account set money=money-100 where card_id= '1234567890'");
			//将给定的 SQL 命令添加到此 Statement 对象的当前命令列表中
			statement.addBatch("update account set money=money+100 where card_id= '0987654321'");
			//将给定的 SQL 命令添加到此 Statement 对象的当前命令列表中
			statement.executeBatch();//批量执行此列表中的命令
			connection.commit();//若无异常爆发提交事务
		} catch (Exception e) {
			try {
				if(connection !=null){
					System.out.println("回滚");//
					connection.rollback();//若sql语句执行过程中发生异常则rollback
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally {
			try {
				if (statement!=null) {
					statement.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (connection!=null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

我们首先初始化表:
jdbc实现事务回滚/提交_第1张图片
执行Test类:
在这里插入图片描述
account表更新成功。
我们故意修改sql语句代码使其出错,然后运行:
在这里插入图片描述
出现异常回滚。
查看account表:
在这里插入图片描述
数据未更新,回滚成功。

你可能感兴趣的:(jdbc实现事务回滚/提交)