直接上代码
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 + "行");}