java - 嵌套尝试 finally 或使用 if 条件尝试哪种方法更好

标签 java jdbc

使用JDBC向数据库中插入记录,有两种方式:

  1. Nested try.. finally :在这种方法中,嵌套 try 和 finally 用于关闭 prepare 语句和连接

    public void performInsert(String insertSQL) {
        try {
            Connection connection = dataSource.getConnection();
            try {
                PreparedStatement insertStmt = connection
                        .prepareStatement(insertSQL);
                try {
                    // bind value to prepare statements
                    insertStmt.executeUpdate();
                } finally {
                    insertStmt.close();
                }
            } finally {
                connection.close();
            }
        } catch (SQLException e) {
            // TODO: handle exception
        }
    }
    
  2. public void performInsertIF(String insertSQL) {
        Connection connection = null;
        PreparedStatement insertStmt = null;
        try {
            connection = dataSource.getConnection();
            insertStmt = connection.prepareStatement(insertSQL);
            // bind value to prepare statements
            insertStmt.executeUpdate();
        }catch (SQLException e) {
            // TODO: handle exception
        } finally {
            if( insertStmt != null) {
                try {
                    insertStmt.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    
            if( connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    

上述两种方法都可以正常工作,但哪种方法更好用,为什么?

最佳答案

在上面的代码中,两种方法都可以正常工作,但第二种方法在某种程度上更好,因为您在调用 close() 之前检查了一个 null 对象。在空对象上调用 close() 将抛出 NullPointerException

但是,现在在 Java 7+ 中,您可以使用一个更好的替代方案,称为 try-with-resources .

关于java - 嵌套尝试 finally 或使用 if 条件尝试哪种方法更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23931890/

相关文章:

java - 在 Vaadin 中打开指向文件的链接

java - 使用 keytool 生成 128 位 key

java - 设置来自 Java 的 PostgreSQL JDBC 连接的连接选项

java - 我的代码显示错误

mysql - 在netbeans中使用jdbc驱动连接新创建的mysql数据库

java - 无法将类型 [org.apache.tomcat.jdbc.pool.DataSource] 的构造函数参数值转换为所需类型 [java.lang.String] :

java - 具有泛型类型的 ViewModel

java - 使用派生参数重载派生类中的 final方法

java - 用其他单词替换某些系列的单词

java - 想要每 24 小时时间间隔在 java 数据库连接中运行线程