Is it ok to open a connection in the init
method and close it in the destroy
method? Also what's the best way to open a connection to a mysql database. Currently I'm using this:开发者_如何学运维
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://" + ipaddress + "?user=" + user + "&password=" + pass);
But I read somewhere that this is inefficient and I should use connection pool. How to do that?
I would strongly suggest using a connection pool, either explicitly (such as c3p0) or one provided by your servlet container.
Open your database connection when you need it, then close it as soon as you can - the connection pool will take care of the real network connection.
Unless you do this, you'll end up with one connection for your whole application - which means you can only process one query at a time, and all your code needs to synchronize around database queries. Surely you want multiple entirely-independent queries to be able to execute simultaneously? You can't do this with a single connection.
As for the best way of opening a connection having configured an appropriate connection pool - you may well still end up using DriverManager.getConnection()
, but specifying the connection pool instead of mysql directly.
精彩评论