簡體   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