惊!Mysql 的回滚还能这么做!
首先呢,常规操作,先创建一个数据库
注意:
1、id是主键
2、id开启自动递增
接下来呢添加一些数据
重点:主程序
连接数据库就省略了,可以参考惊!登陆注册还能这么做
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
try {
//获取链接
conn = JDBCUtils.getCounection();
//开启事务
conn.setAutoCommit(false);
//定义sql
String sql1 = "update account set balance = balance - ? where id = ?";
String sql2 = "update account set balance = balance + ? where id = ?";
//获取执行sql对象
pstmt1 = conn.prepareStatement(sql1);
pstmt2 = conn.prepareStatement(sql2);
//设置参数
pstmt1.setDouble(1,500);//第一个占位符500
pstmt1.setInt(2,1);//第二个占位符是1
pstmt2.setDouble(1,500);
pstmt2.setInt(2,2);
//执行sql
pstmt1.executeUpdate();
//手动制造一个异常
//int i =3/0;
pstmt2.executeUpdate();
//提交事务
conn.commit();
}catch (Exception e){
//事务回滚
try{
if(conn!=null){
conn.rollback();
}
}catch (SQLException e1){
e1.printStackTrace();
}
e.printStackTrace();
}finally {
JDBCUtils.close(pstmt1,conn);
JDBCUtils.close(pstmt2,conn);
}
}
运行完以后呢就会发现钱转账成功了!