ResultSet关闭后不允许操作。原因

时间:2015-08-13 11:59:32

标签: java mysql sql jdbc

我做错了什么?我试图交换rs.close(),pstmt.close(),conn.close()。 我创建了一个PreparedStatement。 但是我仍然无法显示数据库表的内容。如果我删除conn.close(),一切正常!连接有多接近并在jsp上获得输出?

这是我的代码:

    public ResultSet executeFetchQuery(String sql) {
    ResultSet rs = null;
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
        conn = Database.getConnection();
        pstmt = conn.prepareStatement(sql);
        rs = pstmt.executeQuery();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            rs.close();
            pstmt.close();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(PhoneDAO.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }
    return rs;
}


public ArrayList<Phone> getAllPhone() {
    ArrayList<Phone> list = new ArrayList<>();
    String sql = "SELECT * FROM phones.product;";
    ResultSet rs = executeFetchQuery(sql);
    try {
        while (rs.next()) {
            Phone phone = new Phone();
            phone.setId(rs.getInt("id"));
            phone.setName(rs.getString("name"));
            phone.setPrice(rs.getInt("price"));
            phone.setQuantity(rs.getInt("quantity"));
            phone.setDescription(rs.getString("description"));
            System.err.println(phone);
            list.add(phone);
        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    return list;
}

2 个答案:

答案 0 :(得分:0)

 ResultSet rs = executeFetchQuery(sql); 
The above statement closes everything. 

实际上你的代码应该是 DBConnection进行 迭代结果集 存储值/直接显示值(取决于您的需要) 最后关闭连接。 哪种方法是从db访问数据的正确方法。

答案 1 :(得分:0)

此类过程的更常见模式是维护主查询代码之外的连接和语句。这是主要的,因为连接通常是从池中分配的,因为它们创建起来很昂贵,并且不止一次地准备相同的语句是浪费。

这样的事情最有可能有效和正确地发挥作用。

static final Connection conn = Database.getConnection();
static final String sql = "SELECT * FROM phones.product;";
static final PreparedStatement pstmt = conn.prepareStatement(sql);

public ArrayList<Phone> getAllPhone() {
    ArrayList<Phone> list = new ArrayList<>();
    ResultSet rs = pstmt.executeQuery();
    try {
        while (rs.next()) {
            Phone phone = new Phone();
            phone.setId(rs.getInt("id"));
            phone.setName(rs.getString("name"));
            phone.setPrice(rs.getInt("price"));
            phone.setQuantity(rs.getInt("quantity"));
            phone.setDescription(rs.getString("description"));
            System.err.println(phone);
            list.add(phone);
        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
    } finally {
        rs.close();
    }
    return list;
}

请注意ResultSet块中finally是如何关闭以阻止泄漏的。

此模式有各种变体,例如,仅创建连接并在最后一分钟准备语句而不是像我在这里的static final字段。