JDBC事务提交与回滚小练习
需求:zhangsan给lisi转账500元,要求利用事务提交与回滚来规避数据丢失风险
备注:数据库,工具类和配置文件在我的这篇文章内
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class jdbcdemo9 {
public static void main(String[] args) {
PreparedStatement preparedStatement1 = null;
PreparedStatement preparedStatement2 = null;
Connection connections = null;
//数据库连接
try {
connections = JDBC_utils.getConnections();
//开启事务 false开启
connections.setAutoCommit(false);
//第二步 定义sql语句
String sql01 = "update account set balance = balance - ? where id = ?";
String sql02 = "update account set balance = balance + ? where id = ?";
//创建执行sql对象
preparedStatement1 = connections.prepareStatement(sql01);
preparedStatement2 = connections.prepareStatement(sql02);
//set 占位符值
preparedStatement1.setDouble(1, 500);
preparedStatement1.setInt(2, 1);
preparedStatement2.setDouble(1, 500);
preparedStatement2.setInt(2, 2);
//执行sql
preparedStatement1.executeUpdate();
preparedStatement2.executeUpdate();
//手动制造异常!数据回滚 全部失效
int i = 2 / 0;
//提交事务
connections.commit();
} catch (SQLException e) {
//回滚
if (connections != null) {
try {
connections.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
} finally {
JDBC_utils.Close(preparedStatement1, connections);
JDBC_utils.Close(preparedStatement2, connections);
}
}
}