zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Beta版使用说明
    【每日scrum】NO.7
    【每日scrum】NO.6
    【每日scrum】NO.5
    【每日scrum】NO.4
    【每日scrum】NO.3
    【每日scrum】NO.2
    【每日scrum】NO.1
    运行及总结
    测试与调试
  • 原文地址:https://www.cnblogs.com/liclBlog/p/15349572.html
Copyright © 2011-2022 走看看