繁体   English   中英

我们应该将Connection放在1个方法中,将PreparedStatement放在一个单独的方法(Java)中吗?

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

这是我的问题,我需要选择数据,但是数据可能很多,因此也需要选择总结果,因此我需要为相同的字段两次调用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 in 1方法和PreparedStatement放在单独的方法中是一种好习惯。 如果可以的话,那么“我finally需要在getOrderPreparedStatement方法中使用closeStatement吗?”

还是您可以提出更好的解决方案?

尽管将重复任务的代码移到方法中绝对是一个好主意,但是在决定要重用多少代码时,您必须非常小心。

具体而言,在您的示例中,您不应尝试在finally子句中关闭该语句,因为您准备的语句在getOrderPreparedStatement之外将无法使用。

您可以做的另一件事是从方法中删除异常处理代码。 这样可以使方法内部的逻辑更清晰,因此读者可以更轻松地了解自己的意图。 这也将减少代码重复,因为当前catch (SQLException ex)块内的代码是相同的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM