如果應用程序需要是由多個用戶使用的一個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