JDBC RowSets using singleton Connection

Refresh

March 2019

Views

231 time

1

I'm using javax.sql.rowset.JdbcRowSet and com.sun.rowset.JdbcRowSetImpl to manipulate data. Everything works fine, but I'm getting a warning that I might get a resource leak.

Also, I'm using singleton Connection in JdbcRowSet constructor which is always open, but when I use JdbcRowSet close() I can't use it in next method.

Here's the code.

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();
}

When it gets to execute myrs in function2() I get an error:

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

Anyone knows how to solve it?

1 answers

2

Here's the JdbcRowSetImpl implementation of close

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

Since the JdbcRowSetImpl.close() will close the connection, the best way to fit with your current architecture might be to create a JdbcRowSet member or instance singleton that is closed when you expect the connection to be classed. Your function1 and function2 would look like this

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();
    }
}