数据库连接池 c3p0

来源:互联网 发布:手机跑团软件 编辑:程序博客网 时间:2024/05/22 01:44

package com.qrsx.util;

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

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBUtil {
 private static final String DRIVERCLASS="com.mysql.jdbc.Driver";
 private static final String JDBCURL="jdbc:mysql://localhost:3306/test";
 private static final String USERNAME="root";
 private static final String USERPASS="";
 private static Connection connection=null;
 private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
 
 static{
  try {
   dataSource.setDriverClass(DRIVERCLASS);
  } catch (PropertyVetoException e) {
   e.printStackTrace();
  }           
  dataSource.setJdbcUrl(JDBCURL);
  dataSource.setUser(USERNAME);                                 
  dataSource.setPassword(USERPASS);                                 
  // the settings below are optional -- c3p0 can work with defaults
  // 设置初始连接池的大小! 
        dataSource.setInitialPoolSize(2); 
        // 设置连接池的最小值!  
        dataSource.setMinPoolSize(1); 
        // 设置连接池的最大值!  
        dataSource.setMaxPoolSize(10); 
        // 设置连接池中的最大Statements数量! 
        dataSource.setMaxStatements(50); 
        // 设置连接池的最大空闲时间! 
        dataSource.setMaxIdleTime(60);
 }
 /**
  * 得到一个数据库的链接
  * @return
  */
 public static Connection getConnection(){
  try {
   connection=dataSource.getConnection();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  
  return connection;
 }
 /**
  *  将数据库的连接归还连接池
  */
 public static void closeConnection(){
  if(connection!=null)
  try {
   connection.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
}