单连接中的多个语句

时间:2019-02-28 03:00:52

标签: java sql-server

我编写了在单个连接中运行多个语句的代码。第一条语句将检索要循环的ID,第二条语句将使用该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. 我需要注意什么吗?因为除了链接Multiple-statements-single-connection from CodeRanch(已有16年的历史了),我似乎无法找到与此用例有关的任何东西,除了驱动程序支持之外,我不太清楚。

谢谢。

1 个答案:

答案 0 :(得分:1)

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

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