第一步:获取批处理的SQL语句集合:
第一种方式: 使用Statement对象:
public boolean executeBatch(ArrayList<String> sqls) {
Connection conn = null;
Statement stmt = null;
try {
// 得到数据库连接
conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection(); //hibernate
conn.setAutoCommit(false);//关闭自动提交
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
for (int i = 0; i < sqls.size(); i++) {
stmt.addBatch(sqls.get(i));// 将所有的SQL语句添加到PreparedStatement中
}
// 执行SQl语句
stmt.executeBatch();
conn.commit();
conn.setAutoCommit(true);//批量操作完成后打开自动提交功能
}
catch (Exception e1) {
LOGGER.error(e1, e1);
return false;
}
finally {
closeAll(conn, stmt, null);//关闭所有资源
}
return true;
}
第二种方式: 使用PreparedStatement对象:
public boolean executeBatch(ArrayList<String> sqls) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 得到数据库连接
conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
conn.setAutoCommit(false);
for (int i = 0; i < sqls.size(); i++) {
pstmt = conn.prepareStatement(sqls.get(i));
pstmt.addBatch();// 将所有的SQL语句添加到Statement中
}
// 执行SQl语句
pstmt.executeBatch();
conn.commit();
conn.setAutoCommit(true);
}
catch (Exception e1) {
LOGGER.error(e1, e1);
return false;
}...
......
以上两种方式容易SQL注入.第三种方式:与前两种方式写法类似,不过获取SQL语句参数的方法不同,可以有效防止SQL注入,这才是我们需要的:
public boolean executeBatch(int sqlsSize, int len, Object[] objs) { //sqlsSize为需要执行的SQL语句条数,len为参数个数,objs为参数,例子:insert into employee (name, city, phone) values (?, ?, ?)
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 得到数据库连接
conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
conn.setAutoCommit(false);
for (int i = 0; i < sqlsSize; i++) {
pstmt = conn.prepareStatement("insert into employee (name, city, phone) values (?, ?, ?)");
for(int j = 0; j < len; j++) {
pstmt.setObject(j, objs[j]);
}
pstmt.addBatch();// 将所有的SQL语句添加到PreparedStatement中
}
// 执行SQl语句
pstmt.executeBatch();
conn.commit();
conn.setAutoCommit(true);
}
catch (Exception e1) {
LOGGER.error(e1, e1);
return false;
}
finally {
closeAll(conn, pstmt, null);
}
return true;
}