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:


. . . ;


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



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: []

    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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s