我有2个查询,因此通过ResultSet
从Java返回2个createStatement()
。查询就像
SELECT * FROM abc;
SELECT * FROM def;
这些查询在单个createStatement()
中同时运行,如
CreateConnection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select * from ABC; select * from DEF;");
while(rs.next()) {
//Iterate through first resultset
}
rs.close();
stat.close();
conn.close();
如何获取第二个查询返回的下一个ResultSet
?
答案 0 :(得分:2)
使用Statement#getMoreResults
和Statement#getResultSet
方法:
ResultSet rs = stat.executeQuery("select * from ABC; select * from DEF;");
while(rs.next()) {
//Iterate through first resultset
}
rs.close();
if (stat.getMoreResults()) {
rs = stat.getResultSet();
while(rs.next()) {
//Iterate through second resultset
}
}
stat.close();
为了使此方法有效,您应该通过将此属性附加到您的连接网址来为您的连接添加allowMultiQueries=true
属性:
String url = "jdbc:mysql://yourServer:yourPort/yourDatabase?allowMultiQueries=true";
请注意,您可以使用单个Statement
对象按Connection
执行多个查询:
Connection con = ...
List<String> sqlStatements = ... //a list with all the SELECT statements you have
for (String query : sqlStatements) {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
//do your logic here...
}
rs.close();
stmt.close();
}
conn.close();