1. 程式人生 > >jdbc連線池c3p0連線

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