jdbc连接池c3p0连接

public class DataSource {

    private static DataSource datasource;
    private ComboPooledDataSource cpds;

    private DataSource() throws IOException, SQLException, PropertyVetoException { //该类构造时即创建c3p0数据库连接池
        cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver
        cpds.setJdbcUrl("jdbc:mysql://localhost:3306/stopsix_two_phase");
        cpds.setUser("root");
        cpds.setPassword("root");
        cpds.setMinPoolSize(5); //最小连接数目
        cpds.setAcquireIncrement(5); //连接不够时增加数目
        cpds.setMaxPoolSize(20); //最大连接数目
    }

    public static DataSource getInstance() throws IOException, SQLException, PropertyVetoException { //获得单例
        if (datasource == null) {
            datasource = new DataSource();
            return datasource;
        } else {
            return datasource;
        }
    }

    public Connection getConnection() throws SQLException {
        return this.cpds.getConnection();
    }

}

调用:

public class Get {

	public static void main(String[] args) throws IOException, PropertyVetoException {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
            connection = DataSource.getInstance().getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select 1+1 as numb");
             while (resultSet.next()) {
                 System.out.println("numb: " + resultSet.getInt("numb"));
             }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException e) {e.printStackTrace();}
            if (statement != null) try { statement.close(); } catch (SQLException e) {e.printStackTrace();}
            if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();}
        }

	}
}

 

jar包:c3p0-0.9.5.2.jar,mchange-commons-java-0.2.11.jar,mysql-connector-java-5.1.33.jar

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值