/**
* 批量执行sql
*
* @param sqls
*/
public void batchExecute(String[] sqls) {
Connection connection = null;
Statement statement = null;
try {
connection = dataSource.getConnection();
boolean autoCommit = connection.getAutoCommit();
// 设置自动提交为false,手动提交事务,如果不设置,批量插入效率会很低
connection.setAutoCommit(false);
statement = connection.createStatement();
int length = sqls.length;
int count = 0;
for (int i = 0; i < length; i++) {
statement.addBatch(sqls[i]);
count++;
// 每1000条数据提交一次
if (count >= 1000) {
count = 0;
statement.executeBatch();
connection.commit();
statement.clearBatch();
}
}
statement.executeBatch();
connection.commit();
connection.setAutoCommit(autoCommit);
} catch (SQLException e) {
logger.error(e.getMessage());
try {
connection.rollback();
} catch (SQLException e1) {
logger.error(e.getMessage());
}
throw new RuntimeException();
} finally {
try {
statement.close();
connection.close();
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
}
源码地址:
https://gitee.com/boat824109722/rdbms-batch-insert
mysql批量执行Sql,批量插入
最新推荐文章于 2024-06-05 12:15:55 发布