1.连接池原理:
集合中存入指定数量的连接对象,需要使用的时候取出使用,使用完毕放回集合。如果集合中连接对象数量不够则新建连接对象使用。每个使用完的连接对象不会直接删除!!
简单实现
//DataSource.java模拟
//自己模拟的简单的数据源接口(连接池)
//DataSource.java
public interface MyDataSource implements DataSource
{
private static final connection_num = 10;
private LinkedList<Connection> pool = new LinkedList<>();
static //静态加载产生指定数量的连接对象集合
{
for (int i = 1;i <= connection_num ;i++ ) {
Connection conection = JDBCUtils.getConnection();
MyConnection mycon = new MyConnection(connection,pool);
pool.addFirst(mycon);
}
}
public Connection getConnection()
{
// Connection connection;
return pool.removeLast();//pool中存的是MyConnection对象
}
//.............以下省略重写DataSource的空方法
}
//MyConnection.java
//包装设计模式,改进Connection对象的close方法
//MyConnection.java
public class MyConnection implements Connection{
private Connection connection;
private LinkedList<Connection> pool;
public MyConnection(Connection conn, LinkedList<Connection> pool) {
this.conn = conn;
this.pool = pool;
}
/*
将MyConnection对象存进LinkedList对象尾部
*/
@Override
public void close() throws SQLException {
pool.addLast(this);
System.out.println("数据库连接[" + this + "]已经归还到连接池中");
}
//..........省去简单重复的Connection重写方法
}
2.C3P0连接池:
参数 | 说明 |
---|---|
initialPoolSize | 初始连接数 |
maxPoolSize | 最大连接数 |
checkoutTimeout | 最大等待时间 |
maxIdleTime | 最大空闲回收时间 |
初始连接数
:刚创建好连接池的时候准备的连接数量最大连接数
:连接池中最多可以放多少个连接最大等待时间
:连接池中没有连接时最长等待时间最大空闲回收时间
:连接池中的空闲连接多久没有使用就会回收
使用步骤:
-
导入jar包
c3p0-0.9.1.2.jar
-
编写
c3p0-config.xml
配置文件,配置对应参数 -
将配置文件放在src目录下
-
创建连接池对象
ComboPooledDataSource
,使用默认配置或命名配置 -
从连接池中获取连接对象
-
使用连接对象操作数据库
-
关闭资源
public static void main(String[] args)
{
ComboPooledDataSource cpds = new ComboPooledDataSource(str_config_name);
Connection con = cpds.getConnection();
String sql="...";
PreparedStatement pst = con.prepareStatement(sql);
//...............
}
***重复性的获取连接对象代码可以封装在工具类中
3.DRUID连接池
参数 | 说明 |
---|---|
jdbcUrl | 连接数据库的url:mysql : jdbc:mysql://localhost:3306/druid2 |
username | 数据库的用户名 |
password | 数据库的密码 |
driverClassName | 驱动类名。根据url自动识别,这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName(建议配置下) |
initialSize | 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 |
maxActive | 最大连接数量 |
maxIdle | 已经不再使用,配置了也没效果 |
minIdle | 最小连接池数量 |
maxWait | 获取连接时最大等待时间,单位毫秒。 |
使用步骤
-
在src目录下创建一个properties文件,并设置对应参数
-
加载properties文件的内容到Properties对象中
-
创建DRUID连接池,使用配置文件中的参数
-
从DRUID连接池中取出连接
-
执行SQL语句
-
关闭资源
public static void main(String[] args) throws Exception {
InputStream is = demo_druid.class.getResourceAsStream("/druid.properties");
Properties pp = new Properties();
pp.load(is);
DataSource ds = DruidDataSourceFactory.createDataSource(pp);
Connection con = ds.getConnection();
// DatabaseMetaData metaData = con.getMetaData();
String sql = "insert into student(name,age,score) values(?,?,?)";
PreparedStatement pst = con.prepareStatement(sql);
//............
}