簡體   English   中英

使用單例連接的JDBC行集

[英]JDBC RowSets using singleton Connection

我正在使用javax.sql.rowset.JdbcRowSetcom.sun.rowset.JdbcRowSetImpl來處理數據。 一切正常,但是我收到警告,我可能會發生資源泄漏。

另外,我在始終打開的JdbcRowSet構造函數中使用單例連接,但是當我使用JdbcRowSet close()時,不能在下一個方法中使用它。

這是代碼。

public static Connection conn = DBConnection.getInstance()
        .getConnection();



(not the exact work, only a sample code)
private static void function1() {

    try {
        JdbcRowSet myrs = new JdbcRowSetImpl(conn);
        myrs.setCommand("SELECT * FROM `table1`");
        myrs.execute();

        //result iteration

        myrs.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
private static void function2() {
    same as function1 (for example, not really important here)
}

public static void start(){
    function1();
    function2();
}

當它在function2()執行myrs ,出現錯誤:

at com.sun.rowset.JdbcRowSetImpl.execute(Unknown Source)

有人知道如何解決嗎?

這是關閉的JdbcRowSetImpl實現

public void close() throws SQLException {
    if (rs != null)
        rs.close();
    if (ps != null)
        ps.close();
    if (conn != null)
        conn.close();
}

由於JdbcRowSetImpl.close()將關閉連接,因此適合當前體系結構的最佳方法可能是創建一個JdbcRowSet成員或實例單例,在您希望對連接進行分類時將其關閉。 您的function1和function2看起來像這樣

public static Connection conn = DBConnection.getInstance()
    .getConnection();
//Implementation of DBRowSet left as an exercise for the ambitious.
public static JdbcRowSet myrs =  DBRowSet.getInstance(); 

private static void function1() {
    try {
        myrs.setCommand("SELECT * FROM `table1`");
        myrs.execute();
        //result iteration
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
private static void function2() {
    try {
        myrs.setCommand("SELECT * FROM `table2`");
        myrs.execute();
        //result iteration
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM