当前位置: 动力学知识库 > 问答 > 编程问答 >

Should We put Connection in 1 method & PreparedStatement in a seperated method (Java)?

问题描述:

Here is my problem, I need to select data, but the data may be a lot so need to select the total results as well, so i need to call PreparedStatement twice for the same fields. I don't want to repeatedly write the same code twice, so I want put PreparedStatement into a different method. See ex:

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

}

}

Is it a good practice to put Connection in 1 method & PreparedStatement in a seperated method. If it is ok to do that then "do i need to closeStatement in finally in getOrderPreparedStatement method?"

Or can u suggest a better solution?

网友答案:

Although it is definitely a good idea to move the code for repeated tasks into a method, you need to be very careful when deciding how much code to reuse.

Specifically, in your example you should not attempt to close the statement in the finally clause, because the statement that you prepare would be unusable outside the getOrderPreparedStatement.

One thing that you could do differently is dropping the exception-handling code from the method. This would keep the logic inside the method cleaner, so your readers would have easier time understanding your intentions. This would also reduce code duplication, because currently the code inside the catch (SQLException ex) block is identical.

分享给朋友:
您可能感兴趣的文章:
随机阅读: