如果将PreparedStatement与没有任何池的单个公共连接一起使用,我是否可以为每个dml/sql操作重新创建一个实例来保证预处理语句的强大功能?
我的意思是:
for (int i=0; i<1000; i++) {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1, someValue);
preparedStatement.executeQuery();
preparedStatement.close();
}
Run Code Online (Sandbox Code Playgroud)
代替:
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i=0; i<1000; i++) {
preparedStatement.clearParameters();
preparedStatement.setObject(1, someValue);
preparedStatement.executeQuery();
}
preparedStatement.close();
Run Code Online (Sandbox Code Playgroud)
我的问题是因为我想把这段代码放到多线程环境中,你能给我一些建议吗?谢谢
我在我们的代码库上运行了findbugs,它指出还有两个语句仍然需要关闭.在我们运行的代码的这一部分中:
preparedStatement = connection.prepareStatement(query);
Run Code Online (Sandbox Code Playgroud)
对于3个不同的查询,重用prepareStatement.在finally块中,我们关闭资源:
finally{
try{
if (resultSet != null)
resultSet.close();
} catch (Exception e) {
exceptionHandler.ignore(e);
}
try {
if (preparedStatement != null)
preparedStatement.close();
} catch(Exception e) {
exceptionHandler.ignore(e);
}
Run Code Online (Sandbox Code Playgroud)
语句是否应在下一个connection.prepareStatement(query)之前关闭; 或者这个发现者是否谨慎?