DBUtil

dbcp.properties

#Created by JInto - www.guh-software.de
#Fri Mar 25 16:33:12 CST 2011
connectionProperties=useUnicode\=true;characterEncoding\=utf-8
defaultAutoCommit=true
defaultReadOnly=false
defaultTransactionIsolation=READ_COMMITTED
driverClassName=com.mysql.jdbc.Driver
initialSize=10
maxActive=50
maxIdle=20
maxWait=60000
minIdle=5
password=root
type=1
url=jdbc\:mysql\://127.0.0.1\:3306/user_test
username=root

 

DbcpUtil.java

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;


public class DbcpUtil {
	//数据源 
	private static BasicDataSource dataSource;
	
	static {
		Properties properties = new Properties();
		InputStream  in =null;
		try{
		in = Thread.currentThread().getContextClassLoader().
		getResourceAsStream("dbcp.properties");
		
			properties.load(in);
		
//		dataSource.setDriverClassName(properties.getProperty("driverClassName"));
//		dataSource.setUrl(properties.getProperty("url"));
//		dataSource.setUsername(properties.getProperty("username"));
//		dataSource.setPassword(properties.getProperty("password"));
		
		
			dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {		
			e.printStackTrace();
			throw new ExceptionInInitializerError();
		} finally{
			try{
			if(in!=null){
			    in.close();	
			}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	//从连接池中获得连接
	public static Connection getConn() throws SQLException{
		//从数据库连接池中拿到是JDK动态代理
		//JDK代理必须跟目标具有一样的借口
		//使用代理可以改变close方法的行为
		//每个应用程序只能有一个连接池,而且只能初始化一次,而起连接池在初始化的时候自动加载驱动	
		return dataSource.getConnection();	
	}
	//将数据库的这个连接放到连接池里面
	public static void closeConn(Connection conn){
		if(conn!=null){
			try{
				conn.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

}

 

你可能感兴趣的:(java,jdk,sql,mysql,jdbc)