1,事务
-
要么都成功,要么都失败!
-
ACID原则,保证数据的安全。
2,流程
-
开启事务
-
事务提交 commit()
-
事务回滚 rollback()
-
关闭事务
3,代码实现(注册junit)
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
package com.lt.test;
import org.junit.Test;
import java.sql.Connection;
import java.sql.*;
public class TestJdbc3 {
@Test
public void test(){
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8";
String username = "root";
String password = "123456";
Connection connection = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(url,username,password);
connection.setAutoCommit(false);
String sql = "update `count` set money = money - 100 where name = '秦宇';";
connection.prepareStatement(sql).executeUpdate();
String sql2 = "update `count` set money = money + 100 where name = '王照奎';";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();//提交事务
System.out.println("success");
} catch (Exception classNotFoundException) {
//classNotFoundException.printStackTrace();
try{
connection.rollback();
} catch(Exception e){
e.printStackTrace();
}
classNotFoundException.printStackTrace();
} finally {
try{
connection.close();
} catch(SQLException e){
e.printStackTrace();
}
}
}
}