Reputation: 45
I have created connection's object and stored in the hashMap. While executing query on the connection object I retrieve the object from the hashMap. In finally block I close the connection. However, when we come for the second time I again retrieve the connection's object from the hashMap. This time while executing the query I get closed connection exception. If I remove conn.close() from finally, it works. what is the reason behind this? Moreover, when i print the connection's object I get the object.
Upvotes: 0
Views: 216
Reputation: 2490
You don't have to close Connection after each sql statement.
Newly created Connection is in auto-commit mode :
By default, new connections are in auto-commit mode. From Connection.setAutoCommit
doc:
The commit occurs when the statement completes. The time when the statement completes depends on the type of SQL Statement: •For DML statements, such as Insert, Update or Delete, and DDL statements, the statement is complete as soon as it has finished executing. •For Select statements, the statement is complete when the associated result set is closed. •For CallableStatement objects or for statements that return multiple results, the statement is complete when all of the associated result sets have been closed, and all update counts and output parameters have been retrieved.
But if you set auto-commit to false you have to call Connection.commit
method to update database.
Upvotes: 0
Reputation: 394056
If you are re-using the same Connection
object for multiple queries, you shouldn't close the connection after each time you use it, since closing it means the second query will fail.
Therefore, you should either create a new open Connection
for each query, or keep the cached Connection
open (i.e. don't close it in the finally
block).
Upvotes: 1
Reputation: 131
I think you need to move to some implementation of the connection pool.
P.S. It would be helpful to see your code
Upvotes: 0
Reputation: 101
I think you have to go for a connection pool implementation instead of a simple Map of connections. Here when you close a connection after each transaction, the life cycle of the connection ends, and you can not reuse it from the map.
Think of a connection pool which can get you an already opened connection, and return/release the connection back to the pool once your usage is done.
Upvotes: 1