开发者社区> 问答> 正文

rs != null 和 rs.isClosed()的问题:报错

1.我到网上看到有人在写关闭数据库资源的时候建议这么写:

if(rs != null && rs.isClose()){
    rs.close(); //异常处理就不写了
}

题来了,如果rs、conn、st等没有实例化,那么conn.isClose() 就会报异常,而使用 rs != null 也能保证资源的关闭,为什么还有这么麻烦呢?

展开
收起
kun坤 2020-06-09 22:40:05 766 0
1 条回答
写回答
取消 提交回答
  • 建议使用 try-with-resources,相当于try-catch-finally。

    try (Statement stmt = con.createStatement()) {
            ResultSet rs = stmt.executeQuery(query);
    
            while (rs.next()) {
                String coffeeName = rs.getString("COF_NAME");
                int supplierID = rs.getInt("SUP_ID");
                float price = rs.getFloat("PRICE");
                int sales = rs.getInt("SALES");
                int total = rs.getInt("TOTAL");
    
                System.out.println(coffeeName + ", " + supplierID + ", " + 
                                   price + ", " + sales + ", " + total);
            }
        } catch (SQLException e) {
            JDBCTutorialUtilities.printSQLException(e);
        }
    ######“短路与”都不知道?######

    如果rs、conn、st等没有实例化,那么conn.isClose() 就会报异常

    为什么?

    ######简单来说,就是 rs 都没初始化的时候报了异常 rs 就是空,所以不需要关闭,如果rs初始化成功(rs != null)  那么就 close ######正解
    2020-06-09 22:40:09
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载