当前位置:网站首页>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();
}
}
}
}
边栏推荐
- Esp32c3 crash analysis
- Is it safe to buy funds on securities accounts? Where can I buy funds
- 数据库模式笔记 --- 如何在开发中选择合适的数据库+关系型数据库是谁发明的?
- burp 安装 license key not recognized
- In the era of consumer Internet, a few head platforms have been born
- JASMINER X4 1U deep disassembly reveals the secret behind high efficiency and power saving
- AcWing 1128. Messenger solution (shortest path Floyd)
- sql-labs
- Spark source code compilation, cluster deployment and SBT development environment integration in idea
- [real case] trap of program design - beware of large data
猜你喜欢

Notes on hardware design of kt148a voice chip IC

Cs5268 perfectly replaces ag9321mcq typec multi in one docking station solution

pytorch 模型保存的完整例子+pytorch 模型保存只保存可训练参数吗?是(+解决方案)

Jetson XAVIER NX上ResUnet-TensorRT8.2速度与显存记录表(后续不断补充)

HDL design peripheral tools to reduce errors and help you take off!

After writing 100000 lines of code, I sent a long article roast rust

KT148A语音芯片ic的软件参考代码C语言,一线串口
![[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush](/img/e9/f316d02c3cad226055dcdec6781436.jpg)
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush

励志!大凉山小伙全奖直博!论文致谢看哭网友

Development skills of rxjs observable custom operator
随机推荐
Postman interface test practice, these five questions you must know
Resunet tensorrt8.2 speed and video memory record table on Jetson Xavier NX (continuously supplemented later)
Automatically generate VGg image annotation file
【Hot100】22. 括号生成
Review of the latest 2022 research on "deep learning methods for industrial defect detection"
SBT tutorial
Driverless learning (4): Bayesian filtering
Motivation! Big Liangshan boy a remporté le prix Zhibo! Un article de remerciement pour les internautes qui pleurent
Kt148a voice chip instructions, hardware, protocols, common problems, and reference codes
An analysis of the past and present life of the meta universe
Implementing yolox from scratch: dataset class
JASMINER X4 1U deep disassembly reveals the secret behind high efficiency and power saving
Share several map bed websites for everyone to share pictures
想请教一下,我在东莞,到哪里开户比较好?手机开户是安全么?
【Hot100】23. Merge K ascending linked lists
笔记本安装TIA博途V17后出现蓝屏的解决办法
For (Auto A: b) and for (Auto & A: b) usage
Resunnet - tensorrt8.2 Speed and Display record Sheet on Jetson Xavier NX (continuously supplemented)
[kubernetes series] comparison of space and memory usage before and after kubedm reset initialization
[译]深入了解现代web浏览器(一)