如果您的应用程序需要由多个用户使用,则一个connection
可以由一个用户持有,connection pool
因此其中几个用户将重用现有的connection
而不是创建新的connection
,这将消耗时间。关于close()
方法:连接池保持活动状态,如果每次访问后不关闭连接,连接会堆积,如果数量增加,连接池会堵塞,不再接受其他连接!
public class MyDao {
private InitialContext context;
private DataSource datasource;
public MyDao() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
context = new InitialContext();
datasource = (DataSource) context.lookup("datasource name");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
public MyBean getMyBean() throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet res = null;
String sql = "some query";
try {
connection = datasource.getConnection();//pool connection
statement = connection.prepareStatement(sql);
res = statement.executeQuery();
while (res.next()) {
//return true
}
} catch (SQLException ex) {
ex.printStackTrace();
}
finally {
if (rs!= null) try { rs.close(); } catch (SQLException logOrIgnore) {}//result set if any
if (stm!= null) try { stm.close(); } catch (SQLException logOrIgnore) {}//clase statement if any
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}//close connection
}
}
}//close MyDao