【java】關於Statement和ResultSet

來源:互聯網
上載者:User

今天寫程式發現一個問題,錯誤示範如下:

public static void main(String[] args) {
        // TODO Auto-generated method stub
        String driverName = "oracle.jdbc.driver.OracleDriver";
        String url = "jdbc:oracle:thin:@192.168.115.117:1521:ggg";
        String user = "admin";
        String pwd = "123";
        Connection con=null;
        ResultSet rs1,rs2;
        Statement stm;
        try {
            Class.forName(driverName).newInstance();
            con = DriverManager.getConnection(url, user, pwd);
            stm=con.createStatement();
            rs1=stm.executeQuery("select id from table1");
            rs2=stm.executeQuery("select id from table2");//執行此句時就把rs1給關閉了
            while(rs1.next()){ //調試可知,rs1.closed=true,此時執行next()返回false
                System.out.println(rs1.getString("id"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

//輸入為空白,如果把“rs2=.................”這句注釋掉,則可以出現結果。

先看看JDK API裡面是怎麼說的:

public interface Statement

The object used for executing a static SQL statement and returning the results it produces.

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

“在預設情況下,同一時間每個 Statement 對象在只能開啟一個 ResultSet 對象。因此,如果讀取一個 ResultSet 對象與讀取另一個交叉,則這兩個對象必須是由不同的 Statement 對象產生的。如果存在某個語句的開啟的當前 ResultSet 對象,則 Statement 介面中的所有執行方法都會隱式關閉它。”

筆者註:“在預設情況下……”,不知道如何設定非預設情況下……:-)

補充一下:

public ResultSet executeQuery(String sql)                       throws SQLException

Returns:a ResultSet object that contains the data produced by the given query; never null即它的傳回值永遠不會為null。

看來,以後得多看看JDK API協助文檔啊……呵呵,受益匪淺

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.