尝试使用 java 中的 JDBC 资源语句

dev*_*v ツ 3 java exception-handling try-catch

Hive JDBC 有用的一段代码:

       Connection con = null;
       Statement stmt = null

        try {
            Class.forName("org.apache.hive.jdbc.HiveDriver");
            con = DriverManager.getConnection(connectionUri, userName, password);
            stmt = con.createStatement();
            stmt.executeUpdate(query);

        } catch (ClassNotFoundException cex) {
            cex.printStackTrace();

        } catch (SQLException e) {
            e.printStackTrace();

        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

我想删除 try - catch in finally块。

所以我尝试了try-with-resources Statement

        try (Class.forName("org.apache.hive.jdbc.HiveDriver");
            Connection con = DriverManager.getConnection(connectionUri, userName, password);
            Statement stmt = con.createStatement();){

            stmt.executeUpdate(query);

        } catch (ClassNotFoundException cex) {
            cex.printStackTrace();

        } catch (SQLException e) {
            e.printStackTrace();
        } 
Run Code Online (Sandbox Code Playgroud)

我认为这不是正确的方法。

Class.forName("org.apache.hive.jdbc.HiveDriver")不应该在尝试。我应该为此做一个单独的 try-catch 吗?

       try {
            Class.forName("org.apache.hive.jdbc.HiveDriver");

        } catch (ClassNotFoundException cex) {
            cex.printStackTrace();
        }
        try (Connection con = DriverManager.getConnection(connectionUri, userName, password);
            Statement stmt = con.createStatement();){

            stmt.executeUpdate(query);

        } catch (SQLException e) {
            e.printStackTrace();
        } 
Run Code Online (Sandbox Code Playgroud)

这是正确的方法还是我错过了什么?

Jör*_*ink 5

try-with-ressource 背后的想法是关闭一个AutoCloseable类。因此,使用后应关闭的类(资源)的每次使用都可以与 try-with-ressource(例如 Connection)一起使用。您不必手动关闭它(例如在 finally 块中)。

所以是的,你的想法是对的:

  • try/catch for Class.forName("org.apache.hive.jdbc.HiveDriver");- 因为这不是 AutoCloseable
  • try-with-ressource for Connection con = DriverManager.getConnection(connectionUri, userName, password); Statement stmt = con.createStatement();- 因为ConnectionStatement实现 AutoCloseable

参考:https : //docs.oracle.com/javase/7/docs/api/java/lang/Au​​toCloseable.html