这是我的问题,我需要选择数据,但数据可能很多,所以还需要选择总结果,所以我需要为相同的字段调用 PreparedStatement
两次。我不想重复编写相同的代码两次,因此我想将 PreparedStatement
放入不同的方法中。请参阅示例:
public Order getOrders(){
Connection myCon = null;
PreparedStatement preparedStmt=null;
try{
myCon =getUnusedConnection();
String sql="select * from order where name=? ....... limit 0,3";
preparedStmt=myCon.prepareStatement(sql);
getOrderPreparedStatement(name,....);
ResultSet results=preparedStmt.executeQuery();
int rowCount=0;
while(results.next()){
......
rowCount++;
}
if(rowCount==3){
String sql2="select count(*) from Order where name=?....";
preparedStmt=myCon.prepareStatement(sql);
getOrderPreparedStatement(name,....);
ResultSet results2=preparedStmt.executeQuery();
if(results2){
int totalRow=....;
}
}
}
catch (SQLException ex) {
while (ex != null) {
System.out.println ("SQL Exception: " +
ex.getMessage ());
ex = ex.getNextException ();
}
}catch (java.lang.Exception e) {
System.out.println("***ERROR-->" + e.toString());
}
finally {
closeStatement(preparedStmt);
releaseConnection(myCon);
}
return null;
}
public void getOrderPreparedStatement(PreparedStatement preparedStmt, String name....)
{
try{
preparedStmt.setString(name);
... a lot of set field here....
}
catch (SQLException ex) {
while (ex != null) {
System.out.println ("SQL Exception: " +
ex.getMessage ());
ex = ex.getNextException ();
}
}catch (java.lang.Exception e) {
System.out.println("***ERROR-->" + e.toString());
}
finally {
closeStatement(preparedStmt); // do i need to close Statement in finally here
}
}
将 Connection 放在 1 个方法中并将PreparedStatement 放在单独的方法中是否是一个好习惯?如果可以这样做,那么“我需要在 getOrderPreparedStatement
方法中的 finally
中执行 closeStatement
吗?”
或者你能提出更好的解决方案吗?
最佳答案
尽管将重复任务的代码移至方法中绝对是个好主意,但在决定重用多少代码时需要非常小心。
具体来说,在您的示例中,您不应尝试关闭 finally
中的语句子句,因为您准备的语句在 getOrderPreparedStatement
之外无法使用.
您可以做的不同的一件事是从方法中删除异常处理代码。这将使方法内部的逻辑更加清晰,因此您的读者将更容易理解您的意图。这也会减少代码重复,因为目前 catch (SQLException ex)
内的代码块是相同的。
关于java - 我们是否应该将 Connection 放在 1 个方法中,并将PreparedStatement 放在单独的方法中(Java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21660126/