java自定义数据库连接池以及开源连接池C3p0的使用

数据库连接池

数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去。

数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个
一开始现在内存中开辟一块空间(集合) , 一开先往池子里面放置 多个连接对象。 后面需要连接的话,直接从池子里面去。不要去自己创建连接了。 使用完毕, 要记得归还连接。确保连接对象能循环利用。

java自定义数据库连接池以及开源连接池C3p0的使用_第1张图片

###自定义数据库连接池

代码实现

JDBCUtils.java

package com.songdan.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {
	
	static String driverClass = null;
	static String url = null;
	static String name = null;
	static String password= null;
	
	static{
		try {
			//1. 创建一个属性配置对象
			Properties properties = new Properties();
			InputStream is = new FileInputStream("jdbc.properties");
			
			//使用类加载器,去读取src底下的资源文件。 后面在servlet
//			InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
			//导入输入流。
			properties.load(is);
			
			//读取属性
			driverClass = properties.getProperty("driverClass");
			url = properties.getProperty("url");
			name = properties.getProperty("name");
			password = properties.getProperty("password");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取连接对象
	 * @return
	 */
	public static Connection getConn(){
		Connection conn = null;
		try {
			Class.forName(driverClass);
			//静态代码块 ---> 类加载了,就执行。 java.sql.DriverManager.registerDriver(new Driver());
			//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			//DriverManager.getConnection("jdbc:mysql://localhost/test?user=monty&password=greatsqldb");
			//2. 建立连接 参数一: 协议 + 访问的数据库 , 参数二: 用户名 , 参数三: 密码。
			conn = DriverManager.getConnection(url, name, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 释放资源
	 * @param conn
	 * @param st
	 * @param rs
	 */
	public static void release(Connection conn , Statement st , ResultSet rs){
		closeRs(rs);
		closeSt(st);
		closeConn(conn);
	}
	public static void release(Connection conn , Statement st ){
		closeSt(st);
		closeConn(conn);
	}

	
	private static void closeRs(ResultSet rs){
		try {
			if(rs != null){
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			rs = null;
		}
	}
	
	private static void closeSt(Statement st){
		try {
			if(st != null){
				st.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			st = null;
		}
	}
	
	private static void closeConn(Connection conn){
		try {
			if(conn != null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			conn = null;
		}
	}
}

MydataSource.java

package com.songdan.util;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;



/**
 * 这是一个数据库连接池
 * 一开始先往池子里放10个连接
 * 
 * 1.开始创建10个连接
 * 
 * 2.来的程序通过getConnection获取连接
 * 
 * 3.用完之后,使用addBack,归还连接
 * 
 * 4.扩容
 * */

public class MyDataSource	implements DataSource{
	
	List list = new ArrayList();
	
	public MyDataSource(){
		for (int i = 0; i < 10; i++) {
			Connection conn = JDBCUtil.getConn();
			list.add(conn);
		}
	}
	
	//该连接池对外公布的获取连接的方法
	@Override
	public Connection getConnection() throws SQLException {
		// TODO Auto-generated method stub
		//获取连接的时候,先看看是否有连接
		if(list.size() == 0){
			for (int i = 0; i < 10; i++) {
				Connection conn = JDBCUtil.getConn();
				list.add(conn);
			}
		}
		//reomove(0)移出第一个
		Connection conn = list.remove(0);
		return conn;
	}
	//用完之后记得归还
	public void addBack(Connection conn){
		list.add(conn);
	}
	@Override
	public Connection getConnection(String username, String password)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean isWrapperFor(Class iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public  T unwrap(Class iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

}

TestPool.java

package com.songdan.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Test;

import com.songdan.util.JDBCUtil;
import com.songdan.util.MyDataSource;





public class TestPool {
	@Test
	public void testPool() {
		MyDataSource dataSource = new MyDataSource();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			
			conn = dataSource.getConnection();
			String sql = "select * from ";
			
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
		} catch (SQLException e) {
			
			e.printStackTrace();
		} finally {
			try {
				ps.close();
				rs.close();
			} catch (SQLException e) {
				
				e.printStackTrace();
			} finally{
				dataSource.addBack(conn);
			}
		}
	}
}

出现的问题:

1.需要额外记住 addBack方法

2.单例。

3.无法面向接口编程。

UserDao dao = new UserDaoImpl(); dao.insert();

DataSource dataSource = new MyDataSource();

因为接口里面没有定义addBack方法。

4.怎么解决? 以addBack 为切入点。

###解决自定义数据库连接池出现的问题。

由于多了一个addBack 方法,所以使用这个连接池的地方,需要额外记住这个方法,并且还不能面向接口编程。

我们打算修改接口中的那个close方法。 原来的Connection对象的close方法,是真的关闭连接。 打算修改这个close方法,以后在调用close, 并不是真的关闭,而是归还连接对象。

###如何扩展某一个方法?

原有的方法逻辑,不是我们想要的。 想修改自己的逻辑

直接改源码 无法实现。

继承, 必须得知道这个接口的具体实现是谁。

使用装饰者模式

代码实现

MydataSource.java

package com.songdan.util;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;



/**
 * 这是一个数据库连接池
 * 一开始先往池子里放10个连接
 * 
 * 1.开始创建10个连接
 * 
 * 2.来的程序通过getConnection获取连接
 * 
 * 3.用完之后,使用addBack,归还连接
 * 
 * 4.扩容
 * */

public class MyDataSource	implements DataSource{
	
	List list = new ArrayList();
	
	public MyDataSource(){
		for (int i = 0; i < 10; i++) {
			Connection conn = JDBCUtil.getConn();
			list.add(conn);
		}
	}
	
	//该连接池对外公布的获取连接的方法
	@Override
	public Connection getConnection() throws SQLException {
		// TODO Auto-generated method stub
		//获取连接的时候,先看看是否有连接
		if(list.size() == 0){
			for (int i = 0; i < 10; i++) {
				Connection conn = JDBCUtil.getConn();
				list.add(conn);
			}
		}
		//reomove(0)移出第一个
		Connection conn = list.remove(0);
		//在把这个对象抛出去的时候,先对这个对象进行包装
		Connection connection = new ConnectionWraper(conn, list);
		 
		return connection;
	}
	//用完之后记得归还
	public void addBack(Connection conn){
		list.add(conn);
	}
	@Override
	public Connection getConnection(String username, String password)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean isWrapperFor(Class iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public  T unwrap(Class iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

}

ConnectionWraper.java

package com.songdan.util;

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class ConnectionWraper implements  Connection{
	Connection conn = null;
	List list ;
	public ConnectionWraper(Connection connection,List list) {
		// TODO Auto-generated constructor stub
		super();
		this.conn = connection;
		this.list = list;
	}
	
	@Override
	public void close() throws SQLException {
		//conn.close();
		System.out.println("归还连接之前,池子有"+list.size()+"个连接");
		list.add(conn);
		System.out.println("归还连接之后,池子有"+list.size()+"个连接");
	}

	@Override
	public PreparedStatement prepareStatement(String sql) throws SQLException {
		return conn.prepareStatement(sql);
	}
 
	public void setConn(Connection conn) {
		this.conn = conn;
	}

	@Override
	public void clearWarnings() throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void commit() throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Array createArrayOf(String typeName, Object[] elements)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Blob createBlob() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Clob createClob() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public NClob createNClob() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public SQLXML createSQLXML() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Statement createStatement() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Statement createStatement(int resultSetType, int resultSetConcurrency)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Statement createStatement(int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Struct createStruct(String typeName, Object[] attributes)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean getAutoCommit() throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public String getCatalog() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Properties getClientInfo() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getClientInfo(String name) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getHoldability() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public DatabaseMetaData getMetaData() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getTransactionIsolation() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Map> getTypeMap() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public SQLWarning getWarnings() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isClosed() throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isReadOnly() throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isValid(int timeout) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public String nativeSQL(String sql) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CallableStatement prepareCall(String sql) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CallableStatement prepareCall(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CallableStatement prepareCall(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PreparedStatement prepareStatement(String sql, String[] columnNames)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void releaseSavepoint(Savepoint savepoint) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void rollback() throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void rollback(Savepoint savepoint) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setAutoCommit(boolean autoCommit) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setCatalog(String catalog) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setClientInfo(Properties properties)
			throws SQLClientInfoException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setClientInfo(String name, String value)
			throws SQLClientInfoException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setHoldability(int holdability) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setReadOnly(boolean readOnly) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Savepoint setSavepoint() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Savepoint setSavepoint(String name) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setTransactionIsolation(int level) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setTypeMap(Map> map) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean isWrapperFor(Class iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public  T unwrap(Class iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

}

JDBCUtil.java 与上面一致不变

TestPool.java 与·上面一致不变

使用c3p0连接池

src1下创建c3p0-config.xml




	
  
    com.mysql.jdbc.Driver
    jdbc:mysql://localhost/day06
    root
    123456
    
    
    10
    30
    100
    10
    200
  
  
   
   
    50
    100
    50
    1000

    
    0 
    5

    
     
      1
      1
      1
      5
      50
    
  

 

	

TestC3p0Demo02.java

package com.songdan.c3p0;

import java.sql.Connection;
import java.sql.PreparedStatement;

import org.junit.Test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.songdan.util.JDBCUtil02;

public class TestC3p0Demo02 {
	@Test
	public void TestC3p0(){
	
		
		Connection conn = null;
		PreparedStatement ps = null;
		try {	

			//得到连接
			conn = JDBCUtil02.getConnection();
			String sql = "insert into account values(null,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setString(1, "王五");
			ps.setInt(2, 1000);
			
			ps.executeUpdate();
		} catch (Exception e) {
		
			JDBCUtil02.release(conn, ps);
		}
		
	}
}

JDBCUtil02.java

package com.songdan.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCUtil02 {
	
	 static ComboPooledDataSource dataSource = null;
	
	static{
		dataSource = new ComboPooledDataSource();
		
	}
	
	/**
	 * 获取连接对象
	 * @return
	 * @throws SQLException 
	 */
	public static Connection getConn() throws SQLException{
	
		return dataSource.getConnection();
	}
	
	/**
	 * 释放资源
	 * @param conn
	 * @param st
	 * @param rs
	 */
	public static void release(Connection conn , Statement st , ResultSet rs){
		closeRs(rs);
		closeSt(st);
		closeConn(conn);
	}
	public static void release(Connection conn , Statement st ){
		closeSt(st);
		closeConn(conn);
	}

	
	private static void closeRs(ResultSet rs){
		try {
			if(rs != null){
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			rs = null;
		}
	}
	
	private static void closeSt(Statement st){
		try {
			if(st != null){
				st.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			st = null;
		}
	}
	
	private static void closeConn(Connection conn){
		try {
			if(conn != null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			conn = null;
		}
	}
}

使用开源的DBUtils

什么是DBUtils

Commons DbUtils是Apache组织提供的一个对JDBC进行简单封装的开源工具类库,使用它能够简化JDBC应用程序的开发,同时也不会影响程序的性能

怎么用

1. 导入jar包 commons-dbutils-1.4.jar

语法

增删改

        ComboPooledDataSource dataSource = new ComboPooledDataSource();
		
		//dbutils 知识帮我们简化CRUD的代码,但是创建连接的工作,不在它的工作范围
		QueryRunner queryRunner = new QueryRunner(dataSource);
	 	//插入
	     queryRunner.update("insert into account values (null,?,?)","aa",1000);
		//删除
		queryRunner.update("delete from account where id = ?",5);
		//更新
		queryRunner.update("update account set money = ? where id = ?",555,3);

查询

1.直接new接口的匿名实现类

QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());


 Account  account =  queryRunner.query("select * from account where id = ?", new ResultSetHandler(){

 	@Override
 	public Account handle(ResultSet rs) throws SQLException {
 		Account account  =  new Account();
 		while(rs.next()){
 			String name = rs.getString("name");
 			int money = rs.getInt("money");
 			
 			account.setName(name);
 			account.setMoney(money);
 		}
 		return account;
 	}
 	 
  }, 6);
 
 System.out.println(account.toString());

2.直接使用框架已经写好的实现类。

查询单个对象

QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
 //查询单个对象 
Account account = queryRunner.query("select * from account where id = ?", new BeanHandler(Account.class), 8);

查询多个对象

QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource()); 
List list = queryRunner.query("select * from account ", new BeanListHandler(Account.class));

 

你可能感兴趣的:(java)