分布式事务【1】【数据库事务演示】: https://yuanyu.blog.csdn.net/article/details/104218792
/**
* 张三给李四转账100元
*/
@Test
public void transfer() throws SQLException {
Connection conn = null;
Statement stmt = null;
try {
conn = JDBCConnectionUtil.getConnection();
// 将自动提交设置为false
// 若设置为true则数据库将会把每一次数据更新认定为一个事务并自动提交
conn.setAutoCommit(false);
stmt = conn.createStatement();
// 将 “张三” 账户中的金额减少100
stmt.execute("UPDATE account SET money = money - 100 WHERE name = '张三'");
//TODO 发生了异常
//int a = 1/0;
// 将 “李四” 账户中的金额增加100
stmt.execute("UPDATE account SET money = money + 100 WHERE name = '李四'");
// 提交事务
conn.commit();
// 事务提交:转账的两步操作同时成功
} catch (Exception sqle) {
try {
// 发生异常,回滚在本事务中的操做
// 事务回滚:转账的两步操作完全撤销
conn.rollback();
} catch (Exception ignore) {
}
sqle.printStackTrace();
} finally {
stmt.close();
conn.close();
}
}
//JDBCConnectionUtil
public static Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3306/tx?serverTimezone=UTC&characterEncoding=utf-8";
String user = "root";
String password = "123456";
String className = "com.mysql.cj.jdbc.Driver";
try {
Class.forName(className);
} catch (ClassNotFoundException e) {
log.error(e.getMessage());
}
return DriverManager.getConnection(url, user, password);
}