简体   繁体   English

JDBC连接关闭和PreparedStatement关闭

[英]Jdbc connection close and preparedstatement close

Hi all I knew it is a old question but just curious today. 大家好,我知道这是一个老问题,但今天只是好奇。 As we know connection.close will also close preparedStatement(correct me if I am wrong). 我们知道connection.close也会关闭prepareStatement(如果我错了,请纠正我)。 but what if I close connection then close preparedStatement 但是如果我关闭连接然后关闭prepareStatement,该怎么办

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

Will I get a nullpointer exception? 我会得到一个nullpointer异常吗?

Someone was saying depends on your jvm speed.sometimes ps.close() will run ahead and close first before conn.close finish his job and so you wont get nullpointer. 有人说这取决于您的jvm速度。有时ps.close()会先运行并先关闭,然后conn.close完成工作,这样您就不会得到nullpointer。

In order to test that, I have modified the code 为了测试,我修改了代码

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

But I didn't get the nullpointer. 但是我没有得到空指针。

So my question is what happened here if i close conn first and then ps. 所以我的问题是,如果我先关闭conn然后再关闭ps,这里会发生什么。

thanks all. 谢谢大家

The JavaDoc for Statement.close() states: 用于Statement.close()的JavaDoc指出:

Calling the method close on a Statement object that is already closed has no effect. 在已关闭的Statement对象上调用close方法无效。

I would suggest that means an implementation ought to throw no exceptions if your statement has already been closed by a call to Connection.close() . 我建议这意味着,如果您的语句已经被Connection.close()调用关闭,则实现不应抛出异常。

As per the javadoc of Statement Interface 根据语句接口的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.** 

So there won't be any problem if you close an already closed Statement. 因此,如果您关闭一个已经关闭的Statement不会有任何问题。

The behavior is specific to the driver implementation or the connection pooler implementation. 该行为特定于驱动程序实现或连接池实现。 They basically decorate the underlying connection/statement/resultset and keep track of their state. 它们基本上装饰了基础的连接/声明/结果集并跟踪其状态。 So, the implementation can choose to close the dependent objects before closing the primary ones. 因此,实现可以选择在关闭主要对象之前先关闭依赖对象。 Primrose connection pooler used to print warnings about unclosed statements or results when close() method is called on the Connection (which is overridden to return the connection to the pool). Primrose连接池用于在Connection上调用close()方法时打印有关未结束语句或结果的警告(该方法被重写以将连接返回到池)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM