SQL语句:
CREATE TABLE account (
id INT PRIMARY KEY auto_increment,
`name` VARCHAR(40),
money FLOAT
);
INSERT INTO account (`name`,money) VALUES ('A',1000);
INSERT INTO account (`name`,money) VALUES ('B',1000);
INSERT INTO account (`name`,money) VALUES ('C',1000);
#事务机制
start transaction ;
update account set money=money-100 where name='A';
update account set money=money+100 where name='B';
commit ;
rollback ;
package com.jdbc;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JdbcTest3 {
private static String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=Asia/Shanghai" +
"&?useUnicode=true&characterEncoding=utf8&useSSL=false";
private static String username = "root";
private static String password = "1234";
@Test
public void TransactionCommitTest(){
Connection connection = null;
try {
// 1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2、连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);
// 3、通知数据库开启事务,false开启
connection.setAutoCommit(false);
// 4、编写SQL语句
String sqlMinus = "update account set money = money-100 where name='A';";
String sqlAdd = "update account set money = money+100 where name='B';";
// 5、向数据库发送sql的对象Statement PreparedStatement: CRUD
int update = connection.prepareStatement(sqlMinus).executeUpdate();
// int i = 7/0;
int executeUpdate = connection.prepareStatement(sqlAdd).executeUpdate();
System.out.println(update+"====="+executeUpdate);
connection.commit();
} catch (Exception e) {
//如果出现异常,就通知数据库回滚事务
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}finally{
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}