簡體   English   中英

單連接中的多語句

[英]Multiple Statement in single connection

我編寫了在單個連接中運行多個語句的代碼。 第一條語句將檢索要循環並由第二條語句使用的 ID,然后獲得所需的輸出。 例如:

String sql1 = "SELECT ID FROM __TestParent WHERE Status = 'S'";

    try (
        Connection conn = DbConnector.getConnection();
        Statement s = conn.createStatement();
        Statement s2 = conn.createStatement();
        ResultSet rs = s.executeQuery(sql1)
    ) {
            while(rs.next()) {
                String id = String.valueOf(rs.getInt("ID"));
                String sql2 = "SELECT Description FROM __TestChild WHERE FK = " + id;
                try (
                    ResultSet rs2 = s2.executeQuery(sql2)
                ) {
                    while(rs2.next())
                        Util.printLog("INFO",rs2.getString("Description"));

                }catch(SQLTimeoutException sqltoex){
                    Util.printLog("SEVERE",sqltoex);
                }catch(SQLException sqlex){
                    Util.printLog("SEVERE",sqlex);
                }

            }

    }catch(SQLTimeoutException sqltoex){
        Util.printLog("SEVERE",sqltoex);
    }catch(SQLException sqlex){
        Util.printLog("SEVERE",sqlex);
    }
  • Util.printLog 方法是以想要的格式打印消息

代碼運行良好,輸出符合預期。 我想知道的是:

  1. 這是正確的方法,還是/是否有更好的方法來編寫代碼。
  2. 有什么我需要注意的嗎? 因為除了來自 CodeRanch 的 Multiple-statements-single-connection這個鏈接之外,我似乎找不到關於這個用例的任何東西,這是一個 16 歲的線程,除了驅動程序支持我不太清楚。

謝謝。

您實際上可以使用單個查詢和結果集執行您想要的操作:

SELECT c.Description
FROM __TestChild c
INNER JOIN __TestParent p
    ON c.FK = p.ID
WHERE p.Status = 'S';

代碼:

String sql = "SELECT c.Description FROM __TestChild c ";
sql += " INNER JOIN __TestParent p ON c.FK = p.ID ";
sql += "WHERE p.Status = 'S'";

try (
    Connection conn = DbConnector.getConnection();
    Statement s = conn.createStatement();
    ResultSet rs = s.executeQuery(sql)
) {
    while(rs.next()) {
        Util.printLog("INFO", rs.getString("Description"));
    }
} catch(SQLTimeoutException sqltoex) {
    Util.printLog("SEVERE",sqltoex);
} catch(SQLException sqlex) {
    Util.printLog("SEVERE",sqlex);
}

暫無
暫無

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

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