execute 方法返回的结果集数

Number of result sets returned by the method execute

例如,我有一个存储过程,它 returns 基于输入参数的不同数量的结果集。因此,在 Java 中,我使用从语句 class 执行的方法。有没有方法可以确定方法execute()返回的结果集数量?

不幸的是,我认为没有任何函数可以直接检索结果集计数。

如果在处理之前确实需要总计数,一个可能的解决方案是遍历所有结果集,将它们收集到一个数组中,然后在获取计数后在后续循环中处理它们。这是一个有效的(尽管是特定于 postgres 的)演示:

import java.util.List;
import java.util.ArrayList;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ResultSetCountDemo {

    public static void main(String[] args) throws Exception {

        Class.forName("org.postgresql.Driver");

        Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/main", "postgres", args.length >= 1 ? args[0] : "" );

        // execute query
        Statement st = con.createStatement();
        boolean b = st.execute("select 14, 'a' union all select 15, 'b'; select 26, 'x' union all select 27, 'y';");

        // collect and count result sets
        List<ResultSet> rsList = new ArrayList<ResultSet>();
        int count = 0;
        if (b) {
            rsList.add(st.getResultSet());
            for (++count; st.getMoreResults(Statement.KEEP_CURRENT_RESULT); ++count)
                rsList.add(st.getResultSet());
        } // end if
        System.out.println(count+" set"+(count == 1 ? "" : "s"));

        // process and close result sets
        for (int s = 1; s <= count; ++s) {
            ResultSet rs = rsList.get(s-1);
            for (int r = 1; rs.next(); ++r) {
                System.out.println("set "+s+" ("+r+","+1+") == "+rs.getInt(1));
                System.out.println("set "+s+" ("+r+","+2+") == "+rs.getString(2));
            } // end for
            rs.close();
        } // end for

        System.exit(0);

    } // end main()

} // end class ResultSetCountDemo

输出:

2 sets
set 1 (1,1) == 14
set 1 (1,2) == a
set 1 (2,1) == 15
set 1 (2,2) == b
set 2 (1,1) == 26
set 2 (1,2) == x
set 2 (2,1) == 27
set 2 (2,2) == y