关闭ResultSet是否必须?

时间:2013-08-14 09:00:13

标签: jdbc

我写了一个查询,如下所示 -

    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;
    ResultSet rs = null;
    try {

        String fetchOneSQL = "select p.NAME from PAPER p where  p.PAPERID="+paperId;
        dbConnection = icrudResultAnalysis.getConnection();
        preparedStatement = dbConnection.prepareStatement(fetchOneSQL);
        rs = preparedStatement.executeQuery();

        while (rs.next()) {
            Paper paper=new Paper();                
            paper.setName(rs.getString(NAME));              
        }

        // get new records list
        preparedStatement=null;
        rs=null;

        String getListSql="select ib.NAME from ITEMBANK ib  where ib.ITEMBANKID="+itemBankId;
        preparedStatement = dbConnection.prepareStatement(getListSql);
        rs = preparedStatement.executeQuery();

        while (rs.next()) {
            ItemBank itemBankObj=new ItemBank();
            itemBankObj.setName(rs.getString(NAME));
            listItemBanks.add(itemBankObj);
        }

        rs.close();
        preparedStatement.close();
        dbConnection.close();

    } catch (Exception e) {
        LOGGER.error("Exception Occured while fetching All record: "
                + e.getMessage());
    } finally {

        try{
            if (rs!=null){
                rs.close();
            }
        }catch(SQLException e)
        {
            LOGGER.error(RESULTSETCLOSEEXCEPTION    + e.getMessage());
        }

        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        } catch (SQLException e) {
            LOGGER.error(STATEMENTCLOSEEXCEPTION
                    + e.getMessage());
        }
        try {
            if (dbConnection != null) {
                dbConnection.close();
            }
        } catch (SQLException e) {
            LOGGER.error(CONNECTIONCLOSEEXCEPTION
                    + e.getMessage());
        }
    }

在上面的代码中,我通过创建 ResulSet rs = null 将两个select语句用于单个结果集。这是好习惯吗?或者我每次都要关闭ResultSet?关闭ResultSet和使ResultSet为空有什么区别?

2 个答案:

答案 0 :(得分:4)

使用.close()方法后,所有资源必须在使用后关闭!并且resultSet不是例外,除了在这种情况下(来自ResultSet javadoc):

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

在您的情况下,您必须手动.close()第一个打开的结果集,但不必使用第二个;仅resultSet = null设置对变量resultSet的引用等于null,不多也不少。
如果您使用的是Java7,那么Resultset正在实现AutoCloseable,您可以使用此功能以更干净的方式重写代码(查看Oracle doc

答案 1 :(得分:0)

当您重新使用资源(resultSet,PrepareStatement)时,必须先关闭它们 ...而不是将prepare语句设置为NULL。您必须关闭它并且它会自动关闭结果set.There无需显式关闭结果集。