在Java中执行SQL时处理所有异常

uda*_*hny 1 java sql

在Java中执行一个SQL语句涉及许多步骤:

  1. 创建连接
  2. 创建声明
  3. 执行语句,创建结果集
  4. 关闭结果集
  5. 关闭声明
  6. 关闭连接

在每个步骤中都可以抛出SQLException.如果我们要处理所有异常并正确释放所有资源,代码将看起来像这样,4个TRY级别堆叠在彼此的顶部.

try {
     Connection connection = dataSource.getConnection();
     try {
           PreparedStatement statement = connection.prepareStatement("SELECT 1 FROM myTable");
           try {
                ResultSet result = statement.executeQuery();
                try {
                     if (result.next()) {
                           Integer theOne = result.getInt(1);
                     }
                }
                finally {
                     result.close();
                }
           }
           finally {
                statement.close();
           }
     }
     finally {
           connection.close();
     }
}
catch (SQLException e) {
// Handle exception
}
Run Code Online (Sandbox Code Playgroud)

您是否可以提出更好(更短)的方式来执行语句,同时仍然释放所有消耗的资源?

Tom*_*m G 8

如果您使用的是Java 7,那么try with resources语句会缩短这一点,并使其更易于维护:

try (Connection conn = ds.getConnection(); PreparedStatement ps = conn.prepareStatement(queryString); ResultSet rs = ps.execute()) {

} catch (SQLException e) {
    //Log the error somehow
}
Run Code Online (Sandbox Code Playgroud)

请注意,关闭连接将关闭所有关联的StatementsResultSets.

  • 如果您使用连接池,关闭连接可能实际上不会关闭`Statement`和`ResultSet`. (2认同)