当前位置:网站首页>JDBC | Chapter 4: transaction commit and rollback
JDBC | Chapter 4: transaction commit and rollback
2022-07-02 20:24:00 【Mr. dujiu QAQ】
Transaction-JDBC management
JDBC The default is automatic transactions :
perform sql sentence :executeUpdate() ---- Every time executeUpdate Method representative Transaction auto commit
So you have to go through jdbc Of API Manual transactions :
Open transaction :conn.setAutoCommit(false);
Commit transaction :conn.commit();
Roll back the transaction :conn.rollback();
Be careful : Controlling transactions connnection Must be the same
perform sql Of connection With opening transactions connnection It must be the same to control the transaction .
Transaction Example :
import java.sql.*;
public class Jdbc {
public static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
public static final String USER = "root";
public static final String PASSWORD = "123456";
public static void main(String[] args) throws Exception {
//1. Load driver
Class.forName("com.mysql.cj.jdbc.Driver");
//2. Get database connection
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
//3. Operating the database , We will increase, delete, and change inspections
String sql = "insert into class (id, teacher_id) values (?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
try {
// Set transaction auto commit to manual commit
conn.setAutoCommit(false);
for (int i = 20; i < 30; i++) {
preparedStatement.setObject(1, i);
preparedStatement.setObject(2, i);
preparedStatement.addBatch();
}
int [] success = preparedStatement.executeBatch();
System.out.println(success.length);
// Manual manufacturing abnormality
int m = 10 / 0;
for (int i = 30; i < 40; i++) {
preparedStatement.setObject(1, i);
preparedStatement.setObject(2, i);
preparedStatement.addBatch();
}
int [] success2 = preparedStatement.executeBatch();
System.out.println(success2.length);
// Commit transaction
conn.commit();
} catch (Exception e) {
e.printStackTrace();
try {
conn.rollback();
System.out.println("JDBC Transaction rolled back successfully");
} catch (SQLException e1) {
System.out.println("SQLException in rollback" + e1.getMessage());
e1.printStackTrace();
}
} finally {
// Remember to close the database connection resource after executing the database operation
try {
preparedStatement.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Abnormal information :
JDBC Savepoint
Sometimes a transaction may be a complex set of statements , Therefore, you may want to rollback to a special point in the transaction .JDBC Savepoint Help us create checkpoints in transactions (checkpoint), In this way, you can rollback to the specified point . After the transaction is committed or the whole transaction is rolled back , Any savepoints generated for a transaction are automatically released and become invalid . Rollback the transaction to a savepoint , All other savepoints will be automatically released and become invalid .
step :
1. Create checkpoints in transactions
2. Catch checkpoints in exceptions and roll back to checkpoints
Savepoint Example :
import cn.hutool.core.util.StrUtil;
import java.sql.*;
public class Jdbc {
public static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
public static final String USER = "root";
public static final String PASSWORD = "123456";
public static void main(String[] args) throws Exception {
//1. Load driver
Class.forName("com.mysql.cj.jdbc.Driver");
//2. Get database connection
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
//3. Operating the database , We will increase, delete, and change inspections
String classSql = "insert into class (id, teacher_id) values (?,?)";
String userSql = "insert into users (name, age) values (?,?)";
Savepoint savepoint = null;
try {
// Set transaction auto commit to manual commit
conn.setAutoCommit(false);
PreparedStatement preparedStatement1 = conn.prepareStatement(classSql);
for (int i = 20; i < 30; i++) {
preparedStatement1.setObject(1, i);
preparedStatement1.setObject(2, i);
preparedStatement1.addBatch();
}
int [] success = preparedStatement1.executeBatch();
System.out.println(success.length);
// Set rollback point Failure will only roll back users Information
savepoint = conn.setSavepoint(" checkpoint ");
// Manual manufacturing abnormality
int m = 10 / 0;
PreparedStatement preparedStatement2 = conn.prepareStatement(userSql);
preparedStatement2.setObject(1, " Wrist hero ");
preparedStatement2.setObject(2, "24");
preparedStatement2.executeUpdate();
// Commit transaction
conn.commit();
} catch (Exception e) {
e.printStackTrace();
if (StrUtil.isEmptyIfStr(savepoint)) {
// Rollback all updates sql
conn.rollback();
System.out.println("JDBC Transaction rolled back successfully");
} else {
// Rollback to the specified location
conn.rollback(savepoint);
System.out.println("JDBC Transaction rolled back successfully");
conn.commit();
}
} finally {
// Remember to close the database connection resource after executing the database operation
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
边栏推荐
- 在券商账户上买基金安全吗?哪里可以买基金
- KT148A语音芯片ic的软件参考代码C语言,一线串口
- 数据库模式笔记 --- 如何在开发中选择合适的数据库+关系型数据库是谁发明的?
- Attack and defense world PWN question: Echo
- GCC: Graph Contrastive Coding for Graph Neural NetworkPre-Training
- C language linked list -- to be added
- esp32c3 crash分析
- AcWing 1127. Sweet butter solution (shortest path SPFA)
- Jetson XAVIER NX上ResUnet-TensorRT8.2速度与显存记录表(后续不断补充)
- Codeforces Round #771 (Div. 2)(A-C)
猜你喜欢
Implementation of online shopping mall system based on SSM
Review of the latest 2022 research on "deep learning methods for industrial defect detection"
励志!大凉山小伙全奖直博!论文致谢看哭网友
Taiwan SSS Xinchuang sss1700 replaces cmmedia cm6533 24bit 96KHz USB audio codec chip
Properties of expectation and variance
Data preparation for behavior scorecard modeling
[871. Minimum refueling times]
通信人的经典语录,第一条就扎心了……
Kt148a voice chip IC user end self replacement voice method, upper computer
Jetson XAVIER NX上ResUnet-TensorRT8.2速度与显存记录表(后续不断补充)
随机推荐
通信人的经典语录,第一条就扎心了……
[cloud native topic -50]:kubesphere cloud Governance - operation - step by step deployment of microservice based business applications - database middleware MySQL microservice deployment process
AcWing 1128. Messenger solution (shortest path Floyd)
勵志!大凉山小夥全獎直博!論文致謝看哭網友
KT148A语音芯片使用说明、硬件、以及协议、以及常见问题,和参考代码
Driverless learning (4): Bayesian filtering
浏览器缓存机制概述
【JS】获取hash模式下URL的搜索参数
笔记本安装TIA博途V17后出现蓝屏的解决办法
Esp32c3 crash analysis
Basic concept of database, installation and configuration of database, basic use of MySQL, operation of database in the project
【Hot100】21. Merge two ordered linked lists
证券如何在线开户?手机开户是安全么?
在券商账户上买基金安全吗?哪里可以买基金
Postman download and installation
Taiwan SSS Xinchuang sss1700 replaces cmmedia cm6533 24bit 96KHz USB audio codec chip
How to realize the function of detecting browser type in Web System
【实习】解决请求参数过长问题
CRM客户关系管理系统
pytorch 模型保存的完整例子+pytorch 模型保存只保存可训练参数吗?是(+解决方案)