关闭与数据库的连接后的访问结果集

时间:2018-06-21 11:00:01

标签: java sqlite resultset

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

我需要关闭与db的连接并从结果集中检索数据。但是,如果我在return语句结束前将其关闭,则最终无法访问结果集。

2 个答案:

答案 0 :(得分:0)

不要返回ResultSet,使其保持打开足够长的时间,然后将其关闭。最好的方法是将其读入另一个数据结构,例如List,然后返回所述列表:

我还建议使用 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<>();
    }
} 

您的Connections类看起来像这样:

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
}

答案 1 :(得分:-1)

据我所知,更好的方法是在finally中添加trycatch子句并在那里关闭连接。而且,如果通过方法抛出错误,那就更好了。例如

    public ResultSet Connections() throws SQLException {

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

            return rsc;

        } catch (SQLException ex) {
            throw new SQLException(ex.getMessage());

        } finally {
          //your connection closing code here
          conn.close();//it depends upon your code
    }

}