我编写了在单个连接中运行多个语句的代码。第一条语句将检索要循环的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);
}
代码运行正常,并且输出符合预期。我想知道的是:
谢谢。
答案 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);
}