簡體   English   中英

我可以使用相同的JDBC連接,語句和結果集在JDBC中執行兩個查詢

[英]can i use same JDBC connection, statement and resultset to execute two queries in JDBC

我正在驗證用戶

public static boolean login(DataManager dataManager, String userName, String password) {    
    boolean authenticated = false;      
    Connection connection = dataManager.getConnection();        
    if (connection != null) {           
         try {                           
             Statement s = connection.createStatement();
             String sql = "query";                 
             try {                   
                 ResultSet rs = s.executeQuery(sql);                                     
                 try {                      
                     while (rs.next()) {                             
                        String group_code = rs.getString(1);
                        String orgaunit = rs.getString(2);

                        authenticated = true;                            
                     } //end of while()                      
                 } finally {                     
                     rs.close();                     
                 }                   
             } finally {
                 s.close();                  
             }

         } catch(SQLException e) {               
             //System.out.println("Could not login from dataabse:" + e.getMessage());                
         } finally {             
             dataManager.putConnection(connection);                          
         }                  
    } //end of if (connection != null)      
    return authenticated;       
} //end of login()

我正在關閉dataManager.putConnection(connection) 我想問一旦用戶登錄然后我必須更新用戶的狀態並維護日志歷史記錄。 我可以使用這樣的東西嗎?

try {
    Statement s = connection.createStatement();
    String sql = "query";                 
    try {                    
        ResultSet rs = s.executeQuery(sql);                                  
        try {
            while (rs.next()) {                          
                String group_code = rs.getString(1);                                                
                authenticated = true;                            
            } //end of while()  

            if (autherntcated == true) {
                sql = "query2(update status)"; 
                rs = s.executeQuery(sql);

                while (rs.next()) {
                    //dos tuff
                }

                sql = "anotherQuery";
                rs = s.executeQuery(sql);
                while (rs.next()) {
                    //do stuff
                }

            }

        } finally {                      
            rs.close();                      
        }                    
    } finally {
        s.close();                   
    }                
} catch(SQLException e) {
    //System.out.println("Could not login from dataabse:" + e.getMessage());
} finally {              
    dataManager.putConnection(connection);                           
}

意味着使用相同的連接,相同的語句和相同的結果集執行其他查詢或是錯誤的方法?

謝謝。

編輯------------------------------------------------- -------------

if (connection != null) {
    try {
        String sql = "query";
        PreparedStatement prepStatement = connection.prepareStatement(sql);
        try {
            ResultSet rs = prepStatement.executeQuery(sql);                 
            try {
                while (rs.next()) {
                    String group_code = rs.getString(1);
                    authenticated = true;
                } //end of while()
            } finally {                      
                rs.close();                      
            }
        } finally {
            prepStatement.close();                   
        }

        /// Addition   
        if (authenticated == true) {
            updateUser(connection, userName);
        }
    } catch(SQLException e) {
        //System.out.println("Could not login from dataabse:" + e.getMessage());
    } finally {
        dataManager.putConnection(connection);
    }
} //end of if (connection != null)

更新方法:

private static void updateUser(Connection connection, String userName) {

    try {
        String sql = "UPDATE users SET status_code = 'A' WHERE login_id = '" + userName + "'";    
        PreparedStatement prepStatement = connection.prepareStatement(sql);
        try {
            int numberOfRowsUpdated = prepStatement.executeUpdate(sql);                 
        } finally {
            prepStatement.close();                   
        }

        maintainHistory(connection);

    } catch(SQLException e) {
    //System.out.println("Could not login from dataabse:" + e.getMessage());
    }

} //end of updateUser()

maintainHistory:

private static void maintainHistory(Connection connection) {

    try {
        String sql = "INSERT INTO auditlog_user_logins(user_code,logintime,prstid) VALUES ();";
        PreparedStatement prepStatement = connection.prepareStatement(sql);          
        try {            
          int numberOfRowsUpdated = prepStatement.executeUpdate(sql);                   

       } finally {

        prepStatement.close();                   

       }

     } catch(SQLException e) {

         //System.out.println("Could not login from dataabse:" + e.getMessage());

     }

} //end of maintainHistory()

我可以使用相同的JDBC連接語句

是。 您可以在關閉之前重復使用它們。

和結果集

不,這個問題沒有意義。 結果集是執行查詢或更新的結果。 毫無疑問可以重復使用它。 我想你需要在執行下一個查詢或更新之前關閉前面的結果集。

我建議重用連接,因為每次嘗試查詢數據庫時都建立連接可能是一個性能開銷。

至於陳述,我建議切換到PreparedStatement。 它們不僅是緩存的,而且是保護自己免受SQL注入的一種好方法。 因此,事先建立您的查詢,執行它們,並在完成后最終關閉它們。 重用PreparedStatement意味着您要將參數值替換為相同的PreparedStatement並執行相同的PreparedStatement。

例如,如果你有一個PreparedStatement,如:

PreparedStatement preparedStatement = connection.prepareStatement("SELECT [col_names] from [table_name] where [col_1_value] = ? and [col_2_value] = ?")

在這種情況下,只需將新值替換為參數,就可以多次重復使用相同的PreparedStatement 通常,對於您的情況,您將有多個PreparedStatements。 由於這些語句是緩存的,因此當您執行相同的語句時,它們不會對性能產生重大影響。

這是一個很好的教程,可以在您需要的時候向您介紹PreparedStatement: “使用准備好的語句”

結果集 - 我不知道你怎么能重用它。 當你完成它們時關閉它。 根據Javadoc

當生成它的Statement對象關閉,重新執行或用於從多個結果序列中檢索下一個結果時,ResultSet對象將自動關閉。

但是,請確保在使用完畢后關閉連接。 可重用性是一件好事,但資源管理不善

用相同的問題回答了不同的測試用例。

我可以使用相同的JDBC連接,Statement和ResultSet在JDBC中執行兩個查詢

我們不能並行或並發地重用Connection,Statement和ResultSet,如下所示:

Connection con = databaseConnector.getConnection();
PreparedStatement stmt1=con.prepareStatement("select * from emp");  
ResultSet rs1=stmt.executeQuery();  
while(rs1.next()){  // get SQLException in second iteration
System.out.println(rs1.getInt(1)+" "+rs1.getString(2));  
    //As soon as you execute the following query, the previous Statement and ResultSet are implicitly closed.
    // to resolve we the problem, we should not use the above used Connection. We have to use new Connection.
    PreparedStatement stmt2=con.prepareStatement("select * from address");  
    ResultSet rs2=stmt2.executeQuery();  
    System.out.println(rs2.getString(1)+" "+rs2.getString(2));  

}  
  • 關閉一個Connection關閉一個Statement ,當Statement關閉時也會隱式關閉ResultSet
  • 關閉Statement關閉ResultSet但不會關閉Connection。
  • 關閉ReultSet只會自行關閉,而不是Statement
  • 默認情況下,每個Statement只能同時打開一個ResultSet

最佳實踐:

  • 連接不是線程安全的,因此跨請求共享它們不是一個好主意。
  • 打開數據庫連接是很昂貴的,應該使用ConnectionPool來共享連接。
  • 完成ResultSet使用后立即關閉ResultSet

您可以使用UpdatableResultSet

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM