JDBC连接关闭和PreparedStatement关闭

5

大家好,我知道这是一个老问题,但今天我很好奇。我们知道connection.close()也会关闭preparedStatement(如果我错了请纠正我)。但是如果我先关闭connection再关闭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();

但是我没有收到空指针异常。

所以我的问题是如果我先关闭连接再关闭ps,会发生什么。

谢谢大家。


为什么会出现空指针异常?哪个变量变成了null?然而,在关闭资源时应该按照获取的相反顺序关闭,即在这种情况下先关闭PreparedStatement,再关闭Connection(并在关闭PreparedStatement之前关闭ResultSet)。 - user207421
2个回答

5

Statement.close()的JavaDoc文档如下:

在已经关闭的Statement对象上调用close方法没有任何影响。

我认为这意味着,如果你的语句已经通过调用Connection.close()关闭,那么实现应该不会抛出任何异常。


1
根据Statement接口的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.** 

如果您关闭已经关闭的语句,那么不会有任何问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接