在JDBC中获取下一个ResultSet

时间:2014-10-20 14:50:43

标签: java jdbc resultset

我有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

1 个答案:

答案 0 :(得分:2)

使用Statement#getMoreResultsStatement#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();