java - 单个连接中的多个语句
问题描述
我编写了代码以在单个连接中运行多个语句。第一条语句将检索要循环并由第二条语句使用的 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 方法是以所需格式打印消息
代码运行良好,输出符合预期。我想知道的是:
- 这是正确的方法,还是/是否有更好的方法来编写代码。
- 有什么我需要注意的吗?因为我似乎找不到关于这个用例的任何东西,除了来自 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);
}
推荐阅读
- unix - 如何使用 Awk 使用双引号下的列值过滤行
- java - 使用 Spring-boot Application 中的 Spring Security 使用 Active Directory(使用 AD 域)对用户进行身份验证时出现问题
- android - 在 Instagram 中使用分享意图。如何知道用户实际分享或取消了分享活动?
- javascript - Filereader 在读取为 readAsArrayBuffer 时使用正确的编码读取文件
- java - Jackson:如何获取在序列化或反序列化期间解析的完整 JSON 字符串
- python - 在不使用库的情况下用 python 编写图像
- html - 验证 html 中的内联 css
- jquery - 将匿名对象发布到 MVC 操作
- angular - 如何从innerHtml中删除逗号,值来自角度4的JSON?附图片
- django - 在 Django 的模板表单中引入拼写检查