JDBC中开启事务的批量插入操作

mac2024-05-20  34

直接上代码

import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class Batch { private String url; private String user; private String password; public Batch(String url,String user,String password){ this.url = url; this.user = user; this.password = password; } static{ try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public void insertBatch(String[] sqls) throws Exception{ try(Connection connection = DriverManager.getConnection(url, user, password)) { //关闭自动提交,开启事务 connection.setAutoCommit(false); //保存当前的自动提交模式 boolean autoCommit = connection.getAutoCommit(); //关闭自动提交 connection.setAutoCommit(false); try(Statement stmtStatement = connection.createStatement()) { //循环多次执行SQL语句 for(String sql :sqls ){ stmtStatement.addBatch(sql); } //同时提交所有的SQL语句 stmtStatement.executeLargeBatch(); //提交修改 connection.commit(); //复原所有的自动提交模式 connection.setAutoCommit(autoCommit); } //提交事务 connection.commit(); } } }

调用方式 

public static void main(String[] args) throws Exception { String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=DailyProductionDB"; String user = "sa"; String password = "123"; Batch batch = new Batch(url, user, password); String[] sqls = new String[]{ "INSERT INTO dbo.Product( ProductName ,IsEffective ,Remark ,UnitId)VALUES ( '测试','Y','测试',1)", "INSERT INTO dbo.Product( ProductName ,IsEffective ,Remark ,UnitId)VALUES ( '测试','Y','测试',1)", "INSERT INTO dbo.Product( ProductName ,IsEffective ,Remark ,UnitId)VALUES ( '测试','Y','测试',1)", }; try { batch.insertBatch(sqls); } catch (SQLException e) { e.printStackTrace(); } //System.out.println("受影响的行数是:" + count + "行"); }

 

最新回复(0)