JDBC(3)_采用DBCP连接池技术管理连接

DBCP的使用步骤
步骤一:
导包,使用第三方的道具,必须导入相应的jar包。

一般需要导入两个jar包:
  -commons-dbcp-1.x.jar
  -commons-pool-1.x.x.jar

 

步骤二:

使用代码~看看下面代码的演示吧

/*
 * 采用DBCP连接池技术,管理连接
 */

public class DBUtil2 {
	
	private static BasicDataSource ds;
	
	//为不同线程管理连接
	private static ThreadLocal<Connection> t1;
	
	static{
		
		try{
			//从配置文件读取数据库连接的参数
			Properties prop=new Properties();
			InputStream is=DBUtil2.class.getClassLoader().getResourceAsStream("config2.properties");
			
			prop.load(is);
			is.close();
			
			//初始化连接池
			ds=new BasicDataSource();
			
			//加载数据库
			ds.setDriverClassName(prop.getProperty("driver"));
			
			//设置url
			ds.setUrl(prop.getProperty("url"));
			
			//设置数据库用户名和密码
			ds.setUsername(prop.getProperty("user"));
			ds.setPassword(prop.getProperty("psw"));
			
			//其他关于连接数量等等的参数的设置
			ds.setInitialSize(Integer.parseInt(prop.getProperty("initsize")));
			/*此方法不支持已经不支持了?
			 * ds.setMaxActive(Integer.parseInt(prop.getProperty("maxactive")));
			 */
			ds.setMaxWaitMillis(Integer.parseInt(prop.getProperty("maxwait")));
			ds.setMaxIdle(Integer.parseInt(prop.getProperty("maxidle")));
			ds.setMinIdle(Integer.parseInt(prop.getProperty("minidle")));
			
			//初始化线程本地TreadLocal
			t1=new ThreadLocal<Connection>();
						
		}catch(Exception e){
			e.printStackTrace();
			}

	}
	
	public static Connection getConnection() throws SQLException{
		Connection conn=ds.getConnection();//从连接池中取一个连接
		
		t1.set(conn);
		return conn;
	}
	
	public static void closeConnection(){
		try{			
			Connection conn=t1.get();
			if(conn!=null){
				
				//恢复连接为自动提交事务(此处用于事务处理)
				conn.setAutoCommit(true);
		
				/*
				 * 通过连接池获取的Connection的close()方法,
				 * 实际上并没有将连接关闭,而是将该连接归还。
				 */
				conn.close();
				t1.remove();
			}
		}catch(Exception e){
               e.printStackTrace();
               } } }

 

PS:

此处亦用到了ThreadLocal(线程本地)的知识,请参照以下连接

http://www.cnblogs.com/dreamroute/p/5034726.html

posted on 2017-01-04 13:00  LuxxXK  阅读(111)  评论(0)    收藏  举报