Search code examples
javasqliteresultset

Access result Set after closing connection with db


public ResultSet Connections() {

    try {
        conn = this.connect();
        stmt = conn.createStatement();
        //  String sql = "Select * from connections";
        String sql = "SELECT name , pass , ip , port , dbName , dbType FROM connections";
        rsc = stmt.executeQuery(sql);
        rsc.next();

    } catch (SQLException ex) {
        System.out.println("Conns error " + ex);

    }
    return rsc;
} 

I need to close the connection with db and retrieve the data from the resultset. But if i close it before the return statement cant access the Resultset in the end.


Solution

  • Don't return a ResultSet keep it open just long enough and then close it. The best would be to read it into another datastructure, like a List and then return said list:

    Also I would recommend to use try-with-resources-statements:

    public List<Connections> Connections() {
        String sql = "SELECT name , pass , ip , port , dbName , dbType FROM connections";
    
        try(Connection conn = this.connect(); 
            Statement stmt = conn.createStatement()
            ResultSet rsc = stmt.executeQuery(sql)) {
            List<Connections> list = new ArrayList<>();
            while(rsc.next()){
                list.add(new Connections(
                    rsc.getString("name"),
                    rsc.getString("pass"),
                    rsc.getInt("ip"),
                    rsc.getInt("port"),
                    rsc.getString("dbName"),
                    rsc.getInt("dbType")
                ));
            }
            return list;
        } catch (SQLException ex) {
            System.out.println("Conns error " + ex);
            return new ArrayList<>();
        }
    } 
    

    Where your Connections class would somewhat look like this:

    public class Connections{
    
        // fields
    
        public Connections(String name, String pass, int ip, int port, String dbName, int dbType){
             // assing parameters to fields
        }
    
        // getters and setters
    }