【问题标题】:Closing DB connection with try-with-resources java使用 try-with-resources java 关闭数据库连接
【发布时间】:2020-06-17 19:57:37
【问题描述】:

我的数据库有原始的 get 方法。我需要通过它的 id 获取课程,然后关闭连接和语句。

public Course get(int id) throws ClassNotFoundException, SQLException {
        try (Connection connection = ConnectionConfig.getDbConnection();
             PreparedStatement statement = connection.prepareStatement(GET_COURSE)){
            statement.setInt(1, id);
            ResultSet course = statement.executeQuery();
            course.next();
            String result = course.getString(1);
            return new Course(id, result);
        }
    }

我想用 try-with-resources 来做。它会在此代码中工作还是由于块中的 return 语句而无法自动关闭?另一方面,我不想在这个块之外使用 return 因为方法可以返回带有空字段的对象。在这种情况下,哪种方法形式是最有效和最易读的?提前谢谢你,我明白这是一个相当业余的问题)

【问题讨论】:

  • 连接将被关闭

标签: java database connection coding-style try-with-resources


【解决方案1】:

关闭连接的代码通常写在 finally 块中

Connection connection = null;
try {
connection = ConnectionConfig.getDbConnection();
//do all the stuff

}
finally{
connection.close()
}

【讨论】:

    【解决方案2】:

    连接将被 try with resources 块关闭。条件是给定的类实现 AutoCloseable。情况已经如此。

    可以看到here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      • 2019-03-12
      • 2014-12-24
      • 2019-01-18
      • 2011-10-16
      • 2014-05-05
      • 2020-01-01
      相关资源
      最近更新 更多