日期:2014-05-16  浏览次数:20467 次

JDBC + MySQL使用c3p0连接池
    由于前面在使用JDBC + MySQL出现了tool many connections错误!
    下面是JDBC + MySQL使用c3p0连接池的解决方案
   
public class DBUtils {
	
	private static String url = null;
	
	private static String username = null;
	
	private static String pwd = null;
	
	private static DataSource ds_pooled;
	/** 
	 *  加载数据库连接的配置文件和驱动
	 */
	static{
		FileInputStream fis = null;
		
		Properties env = new Properties();
		try {
			fis = new FileInputStream("dbconfig.properties");
			//加载属性文件中的数据库配置信息
			//以=左边作为key值,右边作为value值
			env.load(fis); 
			
			//1. 加载驱动类
			Class.forName(env.getProperty("jdbc.driver"));
			
			url = env.getProperty("jdbc.url");
			username = env.getProperty("jdbc.username");
			pwd = env.getProperty("jdbc.pwd");
			
			//设置连接数据库的配置信息
			DataSource ds_unpooled = DataSources
					.unpooledDataSource(url, username, pwd);
			
			Map<String, Object> pool_conf = new HashMap<String, Object>();
			//设置最大连接数
			pool_conf.put("maxPoolSize", 10);
			ds_pooled = DataSources.pooledDataSource(ds_unpooled,
					pool_conf);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *  获取连接对象
	 */
	public static Connection getConnection() throws SQLException {
		// 2. 设置连接的url,username,pwd
//		return DriverManager.getConnection(url, username, pwd);
		return ds_pooled.getConnection();
	}
	
	/**
	 * 释放连接池资源
	 */
	public static void clearup(){
		if(ds_pooled != null){
			try {
				DataSources.destroy(ds_pooled);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * 资源关闭
	 * 
	 * @param rs
	 * @param stmt
	 * @param conn
	 */
	public static void close(ResultSet rs, Statement stmt
			, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}


下面为测试代码:
public class TestMySQLConnection {
	private static Integer counter = 0;

	public static void main(String[] args){
		for (int i = 1; i <= 20; i++) {
			new Thread(new Runnable() {
				public void run() {
					Connection conn = null;
					try {
						conn = DBUtils.getConnection();
						synchronized (counter) {
							System.out.print(Thread.currentThread().getName());
							System.out.print("    counter = " + counter++
									+ "  conn = " + conn);
							System.out.println();
							
							conn.prepareStatement("select * from t_user");
							
							conn.close();
						}
					} catch (SQLException e) {
						e.printStackTrace();
					}  
				}
			}).start();
		}
	}
}