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