方法execute返回的结果集数

时间:2015-01-04 14:41:10

标签: java mysql jdbc resultset execute

例如,我有一个存储过程,它根据输入参数返回不同数量的结果集。因此,在Java中,我使用Statement类中的execute方法。是否有方法来确定execute()方法返回的结果集数量?

1 个答案:

答案 0 :(得分:1)

我不相信有任何函数允许直接检索结果集计数。不幸的是。

一种可能的解决方案,如果您在处理之前确实需要总计数,那么将迭代遍历所有结果集,将它们收集到一个数组中,然后在获得计数后在后续循环中处理它们。这是一个有效的(虽然是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