如何重用Apache Commons BasicDataSource的现有JDBC连接

时间:2014-08-14 08:49:39

标签: java jdbc connection-pooling apache-commons-dbcp jdbc-pool

虽然我知道Apache DbUtils,但如何使用BasicDataSource.isValid()来回收或重复使用现有连接?

package net.bounceme.dur.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import net.bounceme.dur.data.TableBean;
import org.apache.commons.dbcp2.BasicDataSource;

public class DatabaseQueries {

    private static final Logger log = Logger.getLogger(DatabaseQueries.class.getName());
    private final MyProps properties = new MyProps();
    private Connection connection = null;
    private boolean valid = false;   //never used :(

    public DatabaseQueries() {
    }

    private void connect() throws SQLException {
        Properties p = properties.getProps();
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(p.getProperty("dur.db.driver"));
        dataSource.setUrl(p.getProperty("dur.db.url"));
        dataSource.setUsername(p.getProperty("dur.db.user"));
        dataSource.setPassword(p.getProperty("dur.db.password"));
        connection = dataSource.getConnection();
        valid = connection.isValid(0);   //now what?
    }

    public void close() throws SQLException {
        connection.commit();
        connection.close();
    }

    private TableBean makeBean(ResultSet r) throws SQLException {
        TableBean bean = new TableBean();
        bean = new TableBean();
        bean.setId(r.getInt("id"));
        bean.setCreated(r.getTimestamp("created"));
        return bean;
    }

    public List<TableBean> selectAll(boolean active) throws SQLException {
        connect();  //what if connection is valid?
        String query = "select * from inventory.clients";
        PreparedStatement statement = connection.prepareStatement(query);
        ResultSet resultSet = statement.executeQuery();
        log.info(resultSet.getStatement().toString());
        TableBean bean = null;
        List<TableBean> beans = new ArrayList<>();
        while (resultSet.next()) {
            bean = makeBean(resultSet);
            log.fine(bean.toString());
            beans.add(bean);
        }
        return beans;
    }

    public TableBean getBean(long id) throws SQLException {
        connect();  //what if connection is valid?
        String s = "SELECT * FROM inventory.clients WHERE id = " + id;
        PreparedStatement statement = connection.prepareStatement(s);
        ResultSet resultSet = statement.executeQuery();
        resultSet.next();
        TableBean bean = makeBean(resultSet);
        log.info(bean.toString());
        return bean;
    }

}

虽然我看到the suggestion is to close the connection for each usage,但我想重新使用现有连接,只要它有效。

0 个答案:

没有答案
相关问题