数据库连接池
- 数据库的连接对象创建工作,比较消耗性能。
2.一开始现在内存中开辟一块空间(集合) , 一开先往池子里面放置 多个连接对象。 后面需要连接的话,直接从池子里面去。不要去自己创建连接了。 使用完毕, 要记得归还连接。确保连接对象能循环利用。
下面内容是我搬运别人写的比较好的内容
- 没有池的情况
- 认识池
说明:
1、 池就是一种容纳对象的容器
2、 连接池就是保存数据库连接对象的容器
3、 在连接池中我们会预先创建一定数量的连接对象,当需要数据库连接的时候,只要从数据库连接池中取出一个,使用完毕之后就再放回去,这些连接对象是以一种循环队列来存放的,取的时候从头开始,放回的时候放在尾部。
4、 通过设置最大连接数量来防止系统无止尽的与数据库连接
5、 连接池中可以设置监听机制,用来测试连接的数量
连接池中的属性
3. 连接池的使用
自定义数据库连接池
- 代码实现
package 连接池;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.sql.DataSource;
/**
*
* @author rong
*这是一个数据库连接池
*1. 一开始先往连接池中放10个连接
*2. 来的程序通过getConnection()连接
*3. 用完通过addBack()归还
*4. 扩容
*/
/**
*
* @author rong
*有缺陷
*1. 需要额外记住addBack()方法
*2. 无法面向接口编程
*DaoSource datasource=new MyDataSource();
*
*JAVA多态
*编译时候看左边,运行时候看右边
*解释:编译的时候看接口中有没有定义这个方法,运行的时候是运行继承类口的类中的方法
*/
public class MyDataSource implements DataSource{
List<Connection> list=new ArrayList<Connection>();
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){//连接不够再创建5个
for(int i=0;i<5;i++){
Connection conn = JDBCUtil.getConn();
list.add(conn);
}
}
Connection connection = list.remove(0);//永远移除第一个
return connection;
}
public void addBack(Connection conn){
list.add(conn);
}
//---------------后面的方法暂时用不到-----------------------//
@Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@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 int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public Connection getConnection(String username, String password)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
-
出现的问题:
-
需要额外记住 addBack方法
-
单例。
-
无法面向接口编程。
UserDao dao = new UserDaoImpl();
dao.insert();DataSource dataSource = new MyDataSource();
因为接口里面没有定义addBack方法。
-
怎么解决? 以addBack 为切入点。
-
解决自定义数据库连接池出现的问题。
由于多了一个addBack 方法,所以使用这个连接池的地方,需要额外记住这个方法,并且还不能面向接口编程。
我们打算修改接口中的那个close方法。 原来的Connection对象的close方法,是真的关闭连接。
打算修改这个close方法,以后在调用close, 并不是真的关闭,而是归还连接对象。
如何扩展某一个方法?
原有的方法逻辑,不是我们想要的。 想修改自己的逻辑
-
直接改源码 无法实现。
-
继承, 必须得知道这个接口的具体实现是谁。
-
使用装饰者模式。
开源连接池
DBCP(database connection pool)
-
导入jar文件
-
不使用配置文件:
public void testDBCP01(){ Connection conn = null; PreparedStatement ps = null; try { //1. 构建数据源对象 BasicDataSource dataSource = new BasicDataSource(); //连的是什么类型的数据库, 访问的是哪个数据库 , 用户名, 密码。。 //jdbc:mysql://localhost/bank 主协议:子协议 ://本地/数据库 dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost/bank"); dataSource.setUsername("root"); dataSource.setPassword("root"); //2. 得到连接对象 conn = dataSource.getConnection(); String sql = "insert into account values(null , ? , ?)"; ps = conn.prepareStatement(sql); ps.setString(1, "admin"); ps.setInt(2, 1000); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.release(conn, ps); } }
-
使用配置文件方式:
Connection conn = null; PreparedStatement ps = null; try { BasicDataSourceFactory factory = new BasicDataSourceFactory(); Properties properties = new Properties(); InputStream is = new FileInputStream("src//dbcpconfig.properties"); properties.load(is); DataSource dataSource = factory.createDataSource(properties); //2. 得到连接对象 conn = dataSource.getConnection(); String sql = "insert into account values(null , ? , ?)"; ps = conn.prepareStatement(sql); ps.setString(1, "liangchaowei"); ps.setInt(2, 100); ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally { JDBCUtil.release(conn, ps); }
-
配置文件
dbcpconfig.properties
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc
username=root
password=
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=gbk
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
- C3P0
拷贝jar文件 到 lib目录
不使用配置文件方式
Connection conn = null;
PreparedStatement ps = null;
try {
//1. 创建datasource
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//2. 设置连接数据的信息
//忘记了---> 去以前的代码 ---> jdbc的文档
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost/bank");
dataSource.setUser("root");
dataSource.setPassword("root");
//2. 得到连接对象
conn = dataSource.getConnection();
String sql = "insert into account values(null , ? , ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, "admi234n");
ps.setInt(2, 103200);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.release(conn, ps);
}
使用配置文件方式
package 连接池;
import java.sql.Connection;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* C3P0数据库连接(使用XML作为配置文件)
* 注意:当配置文件的名字为c3p0-config.xml时,在new ComboPooledDataSource()对象
* 时,会自动使用类加载器加载XML文件
*
* @author rong
*
*/
public class C3P0Demo1 {
@Test
public void test1(){
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//注意:
Connection conn=null;
java.sql.PreparedStatement ps=null;
try {
//获取连接对象
conn = comboPooledDataSource.getConnection();
//准备查询sql
String sql="insert into stu value(16,?,?,42)";
//获取statement
ps= conn.prepareStatement(sql);
ps.setString(1, "胖虎");
ps.setString(2, "男");
ps.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.release(conn, ps);
}
}
}
XML配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- default-config 默认的配置, -->
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost/student</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!-- This app is massive! -->
<named-config name="oracle">
<property name="acquireIncrement">50</property>
<property name="initialPoolSize">100</property>
<property name="minPoolSize">50</property>
<property name="maxPoolSize">1000</property>
<!-- intergalactoApp adopts a different approach to configuring statement caching -->
<property name="maxStatements">0</property>
<property name="maxStatementsPerConnection">5</property>
<!-- he's important, but there's only one of him -->
<user-overrides user="master-of-the-universe">
<property name="acquireIncrement">1</property>
<property name="initialPoolSize">1</property>
<property name="minPoolSize">1</property>
<property name="maxPoolSize">5</property>
<property name="maxStatementsPerConnection">50</property>
</user-overrides>
</named-config>
</c3p0-config>
DBUtils
增删改
//dbutils 只是帮我们简化了CRUD 的代码, 但是连接的创建以及获取工作。 不在他的考虑范围
QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
//增加
//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 = ?", 10000000 , 6);
查询(两种方式)
- 直接new接口的匿名实现类
QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
Account account = queryRunner.query("select * from account where id = ?", new ResultSetHandler<Account>(){
//去执行查询,查询到的数据还是在那个result里面,然后调用下面的handle方法,由用户手动封装
@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());
-
直接使用框架已经写好的实现类。
-
查询单个对象
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));
-
ResultSetHandler 常用的实现类
以下两个是使用频率最高的
BeanHandler, 查询到的单个数据封装成一个对象
BeanListHandler, 查询到的多个数据封装 成一个List<对象>
ArrayHandler, 查询到的单个数据封装成一个数组
ArrayListHandler, 查询到的多个数据封装成一个集合 ,集合里面的元素是数组。
MapHandler, 查询到的单个数据封装成一个map
MapListHandler,查询到的多个数据封装成一个集合 ,集合里面的元素是map。
ColumnListHandler
KeyedHandler
ScalarHandler
总结
数据连接池
-
DBCP
不使用配置
使用配置
-
C3P0
不使用配置
使用配置 (必须掌握)
-
自定义连接池
装饰者模式
DBUtils
简化了我们的CRUD , 里面定义了通用的CRUD方法。
queryRunner.update();增删改
queryRunner.query查