让java从Mysql返回多个ResultSet


首先,JDBC对于SQLSERVER来说默认是支持返回,但对于MySql来说,只默认支持存储过程返回多个ResultSet,那对于手写SQL怎么办。

其实很简单,只要一个在连接字符串中加一个参数:allowMultiQueries=true。

代码实现如下:

@Test
public void test01() throws SQLException, ClassNotFoundException {
    String DBDRIVER = "com.mysql.jdbc.Driver";
    String DBURL = "jdbc:mysql://localhost:3306/bookstore?allowMultiQueries=true";
    String DBUSER = "root";
    String DBPASS = "root";

    Connection conn = null;
    Class.forName(DBDRIVER);
    conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
    System.out.println(conn);
    String sql = "SELECT * FROM category;"
            +"SELECT * FROM user;" ;
    Statement stmt = conn.createStatement();

    boolean isResultSet = stmt.execute(sql);
    ResultSet rs = null;
    int count = 0;
    while(true) {
        if(isResultSet) {
            rs = stmt.getResultSet();
            while(rs.next()) {
                System.out.println(rs.getString(1));
            }
            rs.close();
        } else {
            if(stmt.getUpdateCount() == -1) {
                break;
            }
            System.out.printf("Result {} is just a count: {}", count, stmt.getUpdateCount());
        }

        count ++;
        isResultSet = stmt.getMoreResults();
    }
    stmt.close();
    conn.close();
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM