【发布时间】:2010-11-30 07:55:42
【问题描述】:
以下是我获取数据库连接的帮助类:
我已经使用了 here 中描述的 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;
}
}
在 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);
}
现在,我的问题是除了关闭 finally 块中列出的游标(连接/语句/resultSet/preparedStatement)之外,我是否应该费心做任何其他清理工作。
什么是this 清理?我应该在何时何地进行此操作?
如果您发现以上代码有什么问题,请指出。
【问题讨论】:
-
在JDK 7中你不需要关闭preparedStatement,它实现了AutoClosable。 due to this post
-
@AminSh 您的评论具有误导性,实现
AutoClosable的类并不意味着您不需要关闭它。它只是让您可以选择在try-with-resources块中使用该类的对象。
标签: java database database-connection connection-pooling c3p0