5

大家好,我知道这是一个老问题,但今天只是好奇。正如我们所知,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,这里会发生什么。

谢谢大家。

4

2 回答 2

5

状态的 JavaDoc Statement.close()

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

我建议这意味着如果您的语句已经通过调用Connection.close().

于 2012-09-04T07:15:40.230 回答
1

根据语句接口的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-09-04T07:16:57.643 回答