【问题标题】:Jdbc connection close and preparedstatement closejdbc连接关闭和preparedstatement关闭
【发布时间】:2012-08-28 19:31:59
【问题描述】:

大家好,我知道这是一个老问题,但今天只是好奇。正如我们所知,connection.close 也会关闭preparedStatement(如果我错了,请纠正我)。但是如果我关闭连接然后关闭preparedStatement

conn.close();
ps.close();

我会得到一个空指针异常吗?

有人说取决于你的 jvm 速度。有时 ps.close() 会在 conn.close 完成他的工作之前先运行并先关闭,所以你不会得到空指针。

为了测试,我修改了代码

conn.close();
Thread.sleep(5000);//I give 5s to conn.close to finish his work. should be enough
ps.close();

但我没有得到空指针。

所以我的问题是如果我先关闭 conn 然后 ps 会发生什么。

谢谢大家。

【问题讨论】:

  • 为什么会出现空指针异常?什么变量变成了null?但是,您当然应该以相反的获取顺序关闭资源,在这种情况下,PreparedStatementConnection 之前(ResultSetPreparedStatement 之前)。

标签: java jdbc database-connection prepared-statement


【解决方案1】:

Statement.close() 的 JavaDoc 声明:

在已关闭的Statement 对象上调用方法close 无效。

我建议这意味着如果您的语句已通过调用 Connection.close() 关闭,则实现不应抛出异常。

【讨论】:

    【解决方案2】:

    根据语句接口的javadoc

    close
    void close()
               throws SQLExceptionReleases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources. 
    **Calling the method close on a Statement object that is already closed has no effect.** 
    

    所以如果你关闭一个已经关闭的 Statement 不会有任何问题。

    【讨论】:

      猜你喜欢
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多