标签:
java编程学习有一段时间了,今天突然发现以前比较基础的东西掌握的不牢固了,所以特意回顾下DBUtils架构的数据开发
QueryRunner类
private static ComboPooledDataSource ds;
	//线程数据连接管理器
	private static ThreadLocal<Connection> map = new ThreadLocal<Connection>();
	
	static{
		try{
			//使用3cp0数据连接池获取数据资源
			ds = new ComboPooledDataSource();
		}catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	
	public static Connection getConnection() throws SQLException{
		Connection conn = map.get(); //获取到当前线程上绑定的链接
		if(conn==null){
			conn = ds.getConnection();
			map.set(conn);  //把链接绑定到当前线程上
		}
		return conn;
	}
	//开启事务
	public static void startTransaction(){
		try{
			Connection conn = map.get(); //获取到当前线程上绑定的链接
			if(conn==null){
				conn = ds.getConnection();
				map.set(conn);
			}
			conn.setAutoCommit(false);
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	//提交事务
	public static void commitTransaction(){
		try{
			Connection conn = map.get(); //获取到当前线程上绑定的链接
			if(conn!=null){
				conn.commit();
			}
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	//回滚事务
	public static void rollbackTransaction(){
		try{
			Connection conn = map.get(); //获取到当前线程上绑定的链接
			if(conn!=null){
				conn.rollback();
				conn.commit();
			}
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	//关闭连接
	public static void closeConnection(){
		try{
			Connection conn = map.get(); //获取到当前线程上绑定的链接
			if(conn!=null){
				try{
					conn.close();  //求求大家,千万注意
				}finally{
					map.remove();//解除当前线程绑定的资源
				}
			}
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static DataSource getDataSource(){
		return ds;
	}
	
c3p0配置文件
<named-config name="mysql">
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/day16</property>
		<property name="user">root</property>
		<property name="password">root</property>
		
		<property name="acquireIncrement">5</property>
		<property name="initialPoolSize">10</property>
		<property name="minPoolSize">5</property>
		<property name="maxPoolSize">30</property>
	</named-config>
标签:
原文地址:http://www.cnblogs.com/huy360/p/4513346.html