jai*_*jai 30 java database database-connection connection-pooling c3p0
以下是我的帮助类获取数据库连接:
我已经使用了这里描述的C3P0连接池.
public class DBConnection {
private static DataSource dataSource;
private static final String DRIVER_NAME;
private static final String URL;
private static final String UNAME;
private static final String PWD;
static {
final ResourceBundle config = ResourceBundle
.getBundle("props.database");
DRIVER_NAME = config.getString("driverName");
URL = config.getString("url");
UNAME = config.getString("uname");
PWD = config.getString("pwd");
dataSource = setupDataSource();
}
public static Connection getOracleConnection() throws SQLException {
return dataSource.getConnection();
}
private static DataSource setupDataSource() {
ComboPooledDataSource cpds = new ComboPooledDataSource();
try {
cpds.setDriverClass(DRIVER_NAME);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
cpds.setJdbcUrl(URL);
cpds.setUser(UNAME);
cpds.setPassword(PWD);
cpds.setMinPoolSize(5);
cpds.setAcquireIncrement(5);
cpds.setMaxPoolSize(20);
return cpds;
}
}
Run Code Online (Sandbox Code Playgroud)
在DAO我会写这样的东西:
try {
conn = DBConnection.getOracleConnection();
....
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
logger
.logError("Exception occured while closing cursors!", e);
}
Run Code Online (Sandbox Code Playgroud)
现在,我的问题是,除了关闭finally块中列出的游标(connection/statement/resultSet/preparedStatement)之外,我是否应该费心去做任何其他的清理工作.
什么是这个清理?我应该在何时何地这样做?
如果您在上述代码中发现任何错误,请指出.
ska*_*man 24
使用池化数据源,池中的连接实际上不会关闭,它们只会返回池中.但是,当关闭应用程序时,应该正确并实际关闭与数据库的连接,这是最终清理的地方.
顺便说一下,c3p0项目在水中几乎已经死了,我建议你使用Apache Commons DBCP,它仍在维护.
DAO不应负责获取与数据库的连接.他们无法知道什么时候他们被用作更大交易的一部分.您应该将数据源或连接实例传递给DAO.
如果在finally块中关闭的任何调用抛出异常,则不会调用后面的任何异常.每个人都需要在自己的try/catch块中.我将它们作为静态方法放入实用程序类中.
| 归档时间: |
|
| 查看次数: |
73243 次 |
| 最近记录: |