JDBC使用C3P0进行连接池 [英] JDBC Connection pooling using C3P0

查看:209
本文介绍了JDBC使用C3P0进行连接池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的帮助类获取数据库连接:

Following is my helper class to get DB connection:

我使用C3P0连接池,如下所述此处

I've used the C3P0 connection pooling as described here.

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;
    }
}

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)之外的其他操作。

Now, my question is should I bother to do any other clean up other than closing the cursors(connection/statement/resultSet/preparedStatement) listed in the finally block.

什么是 this cleanup ??

What is this cleanup?? When and where should I do this?

如果您在上述代码中发现错误,请指出。

Should you find anything wrong in the above code, please point out.

推荐答案

使用池化数据源,池中的连接实际上并未关闭,它们只是返回到池中。但是,当应用程序关闭时,到数据库的那些连接应该正确并实际关闭,这是最后一次清理的地方。

With a pooled data source, the connections in the pool are not actually closed, they just get returned to the pool. However, when the application is shut down, those connections to the database should be properly and actually closed, which is where the final cleanup comes in.

顺便说一下,c3p0项目在水中几乎死了,我建议您改用 Apache Commons DBCP ,它仍在维护。

Incidentally, the c3p0 project is pretty much dead in the water, I recommend you use Apache Commons DBCP instead, it's still being maintained.

这篇关于JDBC使用C3P0进行连接池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆