C3p0实践

jar包

  1. c3p0-0.9.2.1.jar
  2. mchange-commons-java-0.2.3.4.jar
  3. mysql-connector-java-5.1.28-bin.jar

建立数据库

CREATE TABLE `employee` (
`EMPLOYEEID` bigint(20) NOT NULL AUTO_INCREMENT,
`EMPLOYEENAME` varchar(255) DEFAULT NULL,
PRIMARY KEY (`EMPLOYEEID`)
);

数据源:

package com.dataSource.c3p0;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSource {

private static DataSource     datasource;
    private ComboPooledDataSource cpds;

private DataSource() throws IOException, SQLException, PropertyVetoException {
        cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver
        cpds.setJdbcUrl("jdbc:mysql://localhost/test");
        cpds.setUser("root");
        cpds.setPassword("root");

// the settings below are optional -- c3p0 can work with defaults
        cpds.setMinPoolSize(5);
        cpds.setAcquireIncrement(5);
        cpds.setMaxPoolSize(20);
        cpds.setMaxStatements(180);

}

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

}

测试主程序

package com.dataSource.c3p0;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class C3P0DataSourceExample {

public static void main(String[] args) throws PropertyVetoException, SQLException, IOException {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DataSource.getInstance().getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select * from employee");
              while (resultSet.next()) {
                  System.out.println("employeeid: " + resultSet.getString("employeeid"));
                  System.out.println("employeename: " + resultSet.getString("employeename"));
              }
        } 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();}
        }
    }
}

输出:

employeeid: 25
employeename: rock
employeeid: 29
employeename: mary

上一篇:uva 12253 - Simple Encryption(dfs)


下一篇:hdu 4465 Candy 2012 成都现场赛