我编写了在单个连接中运行多个语句的代码。第一个语句将检索要循环的 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方法是以想要的格式打印消息
代码运行得很好,输出也符合预期。我想知道的是:
- 这是正确的方法吗?或者是否有更好的方法来编写代码。
- 有什么我需要注意的吗?因为除了此链接 Multiple-statements-single-connection from CodeRanch 之外,我似乎无法找到有关此用例的任何信息。这是 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);
}
关于java - 单连接中的多条语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54917751/