【问题标题】:How to close the connection properly?如何正确关闭连接?
【发布时间】:2014-08-01 20:55:26
【问题描述】:

这个问题已经被问过很多次了,有很多资源都在讨论这个问题。但这仍然让我担心,因为我认为 close() 无法正常工作。

PreparedStatemet pstmt = null;
try {
  pstmt = conn.prepareStatement(query);
  ...
  pstmt.close();
  conn.close();
} catch(...) {
  ...
} finally {
   if(pstmt != null) {
      try {
        pstmt.close();
      } catch (SQLException e) {
        pstmt = null;
      }
   }

   if(conn != null) {
      try {
         conn.close();
       } catch (SQLException e) {
         conn = null;
       }
    }

    System.out.println("PreparedStatement: " + pstmt);
    System.out.println("Connection: " + conn);
}

所以我希望它会打印出 null;但它会不断打印出查询字符串和数据库的连接路径。

【问题讨论】:

  • 为什么?它可以打印出任何它喜欢的东西。您的期望显然是错误的。
  • 对不起,我不明白你的意思。我认为当我们关闭 ptsmt 和 conn 时;他们都应该为空,不是吗?
  • 没有。 (a) 当您将它们设置为 null 时,引用变为 null。不然。 (b) 您看到的是在非空引用上调用 toString() 的结果,该引用可以是相关类喜欢的任何内容。
  • 哦,我明白了。感谢您的澄清。

标签: jdbc connection


【解决方案1】:

你的代码在这里

try {
  PreparedStatemet pstmt = null;

创建一个不应在 finally 块中可见的 pstmt,因为它是另一个范围内的局部变量。

您可能在 try catch 块之外的某个地方还有另一个 pstmt。这在 finally 块中弄乱了您的支票。

尝试在 try 块中注释掉 PreparedStatemet pstmt = null; 以查看您的代码是否仍在构建,这将帮助您确定 pstmt 的覆盖声明到底在哪里。

编辑: 关闭准备好的语句/连接并不意味着这些值将被重置。您的连接和准备好的语句现在确实已关闭,因为您没有将它们设置为 null ,因此仍在打印存储在其中的数据值。这应该不是问题。

虽然不是什么大问题,但您也可以在关闭它们时将 conn 和 pstmt 设置为 null,这也会清除这些变量使用的本地内存。但是请记住,当您进行关闭调用时,连接仍然已经关闭。

【讨论】:

  • 我的错字,我的 PreparedStatement 在 try-catch 块之外。我现在编辑了代码
猜你喜欢
  • 1970-01-01
  • 2018-02-14
  • 2023-03-22
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-21
相关资源
最近更新 更多