作者:蓝沫 | 来源:互联网 | 2023-02-07 00:04
对于数据库的批处理,首先需要做的是查询数据库是否支持批处理下面是实现的代码***判断数据库是否支持批处理*@paramcon*@return*publicsta
对于数据库的批处理,首先需要做的是查询数据库是否支持批处理
下面是实现的代码
/**
* 判断数据库是否支持批处理
* @param con
* @return
*/
public static boolean supportBatch(Connection con){
try {
DatabaseMetaData md = con.getMetaData();
return md.supportsBatchUpdates();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* 执行一批SQL语句
* @param con 数据库的连接
* @param sqls 待执行的SQL数组
* @return
*/
public static int[] goBatch(Connection con, String[] sqls){
if (sqls == null){
return null;
}
Statement sm = null;
try {
sm = con.createStatement();
for (int i=0; i sm.addBatch(sqls[i]);
}
return sm.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
OperateDB.closeStatement(sm);
}
return null;
}
关于sql语句的批处理,上面只是一个简单的代码,具体开发的时候,对于sql语句的多条处理,最好的方式是使用事务进行处理,这样可以让sql语句的执行一致。并且在出现异常的时候可以进行事务回滚。还有值得一提的是,关于Statement和prepareStatement对sql语句进行操作的时候,最好是使用prepareStatement。具体的原因在于
1、PrepareStatement 提高性能
2、提高代码的可读性和可维护性
3、安全性 PrepareStatement防止了SQL注入,提高了程序的安全性。
所以在进行sql操作的时候尽量使用prepareStatement