事务处理
考虑我们有下面一个MySQL表:
CREATE TABLE `money` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '',
`amount` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
表里面有两条数据:
提示:不熟悉MySQL事务的同学可以到我们的MySQL教程进行学习。
下面展示两个用户之间转账的例子:
import java.sql.*;
public class MyClass {
//驱动字符串
final static String driverStr="com.mysql.cj.jdbc.Driver";
final static String dbHost = "192.168.61.125"; // 主机 可为ip地址
final static String dbUserName = "root"; // 用户
final static String dbPassword = "123456"; // 密码
final static String dbPort = "3306"; // 端口
final static String dbName = "mydb"; // 数据库名
final static String connStr="jdbc:mysql://"+ dbHost +":"+ dbPort +"/"+ dbName +"?useSSL=false&serverTimezone=UTC";
public static void main(String[] args){
MyClass obj = new MyClass();
Connection conn = obj.connect();
int amount = 1500; // 转账金额
String sql1 = "UPDATE money SET amount = amount+"+amount+" WHERE name=\"John\"";
String sql2 = "UPDATE money SET amount = amount-"+amount+" WHERE name=\"Tom\"";
try {
conn.setAutoCommit(false); // 开启事务,禁止自动提交
Statement statement = conn.createStatement();
statement.addBatch(sql1);
statement.addBatch(sql2);
statement.executeBatch();
conn.commit(); //执行成功,提交事务
System.out.println("执行成功");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 链接
protected Connection connect () {
Connection conn = null;
try{
Class.forName(MyClass.driverStr); // 加载驱动
conn = DriverManager.getConnection(MyClass.connStr,MyClass.dbUserName,MyClass.dbPassword); // 连接
System.out.println("连接成功");
}catch(Exception ex){
System.out.println("连接失败");
System.out.println(ex.toString());
}
return conn;
}
}
转账成功输出如下:
提示:不懂编译的同学查看:数据库连接一章
这时候可看到两条记录都已经变更: