Execute multiple queries using a single JDBC Statement object

前端 未结 5 2065
说谎
说谎 2021-01-31 17:41

In JDBC, can I use single Statement object to call executeQuery(\"\") multiple times? Is it safe? Or should I close the statement object after each que

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 17:54

    Firstly I am confused about your code

    s = con.prepareStatement();
    

    Is it work well?I can't find such function in JAVA API,at least one parameter is needed.Maybe you want to invoke this function

    s = con.createStatement();
    

    I just ran my code to access DB2 for twice with one single Statement instance without close it between two operation.It's work well.I think you can try it yourself too.

        String sql = "";
        String sql2 = "";
        String driver = "com.ibm.db2.jcc.DB2Driver";
        String url = "jdbc:db2://ip:port/DBNAME";
        String user = "user";
        String password = "password";
        Class.forName(driver).newInstance();
        Connection conn = DriverManager.getConnection(url, user, password);
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        int count = 0;
        while (resultSet.next()) {
            count++;
        }
        System.out.println("Result row count of query number one is: " + count);
        count = 0;
        resultSet = statement.executeQuery(sql2);
        while (resultSet.next()) {
            count++;
        }
        System.out.println("Result row count of query number two is: " + count);
    

提交回复
热议问题