如果应用程序需要是由多个用户使用的一个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
请您在本教程的'close()'方法中提供伪代码代码吗? – Asif 2012-04-11 14:41:55
我已经编辑了我的答案,希望对你有帮助。在@BalusC的教程[link](http://balusc.blogspot.in/2008/07/dao-tutorial-data-layer.html)中,我看到连接在** DAO实用程序类中关闭* * – mykey 2012-04-11 14:51:12
'DataSource'和'Connection#getConnection()'方法在我脑海中已经清楚了,我也在使用它们,但是我的问题是'close()'方法, Methos用于关闭连接,ResultSet和Statement对象,但是我想根据Connection Pooling'重写它...... Connection Pooling的_updated_' close()会是什么? – Asif 2012-04-11 15:18:09