java 批量插入10条数据在有事务的情况下可没有可能出现插入成功9条 失败一条的情况
在有事务的情况下,如果所有的插入操作都在同一个事务中执行,那么要么全部插入成功,要么全部插入失败。只有在事务提交之前发生了异常,才可能出现部分插入成功的情况。
以下是一个示例代码,使用 JDBC 和事务来批量插入 10 条数据:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class BatchInsertExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection(url, username, password);
connection.setAutoCommit(false); // 设置事务为手动提交
String sql = "INSERT INTO mytable (column1, column2) VALUES (?, ?)";
preparedStatement = connection.prepareStatement(sql);
for (int i = 1; i <= 10; i++) {
preparedStatement.setString(1, "Value " + i);
preparedStatement.setString(2, "Value " + i);
preparedStatement.addBatch(); // 添加批处理任务
}
int[] result = preparedStatement.executeBatch(); // 执行批处理任务
connection.commit(); // 提交事务
System.out.println("成功插入 " + result.length + " 条数据");
} catch (SQLException e) {
e.printStackTrace();
try {
if (connection != null) {
connection.rollback(); // 回滚事务
}
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
在上述代码中,首先通过 connection.setAutoCommit(false) 将事务设置为手动提交模式,然后在插入数据之前调用 connection.prepareStatement(sql) 创建预编译的 SQL 语句。接下来,使用 preparedStatement.addBatch() 将每条插入语句添加到批处理任务中。最后,通过 preparedStatement.executeBatch() 执行批处理任务,并将结果保存到 result 数组中。
如果在循环过程中发生了异常,connection.rollback() 会回滚事务,导致所有的插入操作都失败。否则,connection.commit() 会提交事务,使得所有的插入操作都成功。
请注意,上述代码仅为示例,实际情况需要根据数据库驱动和数据库类型进行适当调整
原文地址: https://www.cveoy.top/t/topic/hKsG 著作权归作者所有。请勿转载和采集!