首页 > 解决方案 > 单个连接中的多个语句

问题描述

我编写了代码以在单个连接中运行多个语句。第一条语句将检索要循环并由第二条语句使用的 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);
    }

代码运行良好,输出符合预期。我想知道的是:

  1. 这是正确的方法,还是/是否有更好的方法来编写代码。
  2. 有什么我需要注意的吗?因为我似乎找不到关于这个用例的任何东西,除了来自 CodeRanch 的这个链接 Multiple-statements-single-connection是 16 岁的线程,除了驱动程序支持之外我不太清楚。

谢谢。

标签: javasql-server

解决方案


您实际上可以使用单个查询和结果集执行您想要的操作:

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);
}

推荐阅读