Reputation: 7435
So far all the JDBC code I've seen creates and closes a connection every time. However, I'm wondering if that is necessary because my code seems to work perfectly fine and I'm reusing the same connection each time:
Is this a bad way to do this?
public static int getCount() {
synchronized (DATABASE_ACCESS_LOCK) {
try (ResultSet rs = QUERY.executeQuery("SELECT COUNT(1) FROM " + TABLE_CLIENTS)) {
return rs.getInt(1);
} catch (SQLException ex) {
ex.printStackTrace();
return -1;
}
}
}
Upvotes: 3
Views: 136
Reputation: 150238
You should generally release your database connection when you leave an active scope of work. Database connections are expensive resources. Holding them longer than necessary makes the job of a connection pool manager that much harder.
If you are performing several DB operations together it is quite reasonable to use the same DB connection for all of those operations. Once that group of operations is done, release the connection.
Upvotes: 5