0

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

    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 为空有什么区别?

4

2 回答 2

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()打开第一个结果集,但不必手动使用第二个结果集;对变量equals进行resultSet = null唯一的集合引用,不多不少。 如果您使用的是 Java7,Resultset 正在实现AutoCloseable,您可以使用此功能以更简洁的方式重写您的代码(查看Oracle 文档resultSetnull

于 2013-08-14T18:57:08.097 回答
0

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

于 2013-08-15T05:48:47.590 回答