Common mistake in JDBC programming

JDBC is something every java developer often encounters in his day to day life. I really admire people who never forget to close a connection. But many of us are careful enough to close the resultset, statement as well as connection in the finally block, somewhat like below:

try{

. . . ;

}finally{

if(rs!=null) rs.close();

if(stmt!=null) stmt.close();

if(conn!=null) conn.close();

}

Do you think there is really a need of doing all this? The answer is no.

When you close a statement, the associated result set is automatically closed. Similarly if you close the connection, all statements of that connection are automatically closed.

So there is no need to close all the three, result set, statement and connection.

Enjoy Learning

Kamlesh

Advertisements

2 thoughts on “Common mistake in JDBC programming

  1. Kamlesh,

    The above mention scenario will not be true for all. for connection pooling it is always advisable to close the resources separately before closing the connection.

    courtesy: [http://java-x.blogspot.com/2006/03/java-memory-leaks.html]

    ResultSet and Statement Objects
    JDBC ResultSet and Statement objects will be closed when the connection that created them is closed. However, while using pooled connections, if close() is invoked on the connection, the connection will be returned to the connection pool rather than being closed. Consequently, the ResultSet and Statement objects created by the connection will not be closed automatically, and are a potential cause of memory leaks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s