简体   繁体   中英

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). but what if I close connection then close preparedStatement

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

Will I get a nullpointer exception?

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.

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.

thanks all.

The JavaDoc for Statement.close() states:

Calling the method close on a Statement object that is already closed has no effect.

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() .

As per the javadoc of Statement Interface

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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