批处理设置回滚点:
import java.sql.*;
import java.util.LinkedList;
public class TestTransaction2 {
private static String driver ="com.mysql.cj.jdbc.Driver";
private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useServerPrepStmts=true&cachePrepStmts=true&&rewriteBatchedStatements=true";
private static String user="root";
private static String password="root";
public static void main(String[] args) {
testAddBatch();
}
public static void testAddBatch(){
Connection connection = null;
PreparedStatement preparedStatement=null;
LinkedList<Savepoint> savepoints =new LinkedList<Savepoint>();
try{
Class.forName(driver);
connection = DriverManager.getConnection(url, user,password);
connection.setAutoCommit(false);
String sql="insert into dept values (DEFAULT ,?,?)";
preparedStatement = connection.prepareStatement(sql);
for (int i = 1; i <= 10663; i++) {
preparedStatement.setString(1, "name");
preparedStatement.setString(2, "loc");
preparedStatement.addBatch();
if(i%1000==0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
Savepoint savepoint = connection.setSavepoint();
savepoints.addLast(savepoint);
}
if(i ==10001){
int x =1/0;
}
}
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}catch (Exception e){
if(null != connection){
try {
Savepoint sp = savepoints.get(4);
if(null != sp){
connection.rollback(sp);
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
e.printStackTrace();
}finally {
if(null != connection){
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != preparedStatement){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}