What is the best way to manage a database connection in a Java servlet?
Currently, I simply open a connection in the init()
function, and then close it
A connection pool associated with a Data source should do the trick. You can get hold of the connection from the dataSource in the servlet request method(doget
/dopost
, etc).
dbcp, c3p0 and many other connection pools can do what you're looking for. While you're pooling connections, you might want to pool Statements and PreparedStatements; Also, if you're a READ HEAVY environment as you indicated, you might want to cache some of the results using something like ehcache.
BR,
~A