一、数据库连接池
创建数据库连接对象需要消耗比较多时间和内存,连接池开辟一个池,在池中放置一定数量的连接对象,用户使用连接对象后,连接不会直接销毁,而是回到池中,做其它操作时可以直接利用,减少连接对象的创建次数,从而提高程序的性能。
常用连接池:
C3P0 开源,性能较好,高并发情况下比较稳定。
DBCP 开源,性能较好
Druid 阿里巴巴开发的
Proxool
此次使用c3p0, 使用c3p0需要两个jar包 和 mysql驱动的jar包,可以从官网上获取
- 将这三个jar包加入web项目lib目录下
- 在src目录下创建c3p0-config.xml(最好不要修改名字),加入相应的配置
- 创建ComboPooledDataSource对象,调用getConnection()函数获得连接对象
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<!-- 必填 -->
<!-- 驱动类 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<!-- URL -->
<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb?useSSL=false</property>
<!-- 账号 -->
<property name="user">myaccount</property>
<!-- 密码 -->
<property name="password">mypassword</property>
<!-- 可选 -->
<!-- 初始连接数 -->
<property name="initialPoolSize">10</property>
<!-- 最大闲置时间 -->
<property name="maxIdleTime">30</property>
<!-- 最大连接数 -->
<property name="maxPoolSize">100</property>
<!-- 最小连接数 -->
<property name="minPoolSize">10</property>
<!-- 最大SQL语句数 -->
<property name="maxStatements">200</property>
</default-config>
</c3p0-config>
@Test
public void testC3p0() {
ComboPooledDataSource pool = new ComboPooledDataSource();
try {
Connection connection = pool.getConnection();
System.out.println(connection);
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
若控制台打印出对象,则配置c3p0数据池成功
二、 使用DBUtils jar包获得对数据库的简单操作
- 加入DBUtils jar包 ,创建ComboPooledDataSource对象,并作为参数传入,创建QueryRunner对象
- 增删改都是使用 queryRunner对象的update方法
update(SQL语句,Object… 占位符参数) 查询使用query 方法
query(SQL语句,Handler对象,占位符参数);
handler对象有三种
BeanListHandler 处理SQL语句,返回Java对象集合
BeanHandler 处理SQL语句,返回一个Java对象
ResultSetHandler 通过ResultSet进行查询附 DBUtils对数据库增删改查的封装类
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DBUtils {
private static DataSource dataSource = null;
private static QueryRunner queryRunner = null;
static {
dataSource = new ComboPooledDataSource();
queryRunner = new QueryRunner(dataSource);
}
public static int update(String sql, Object...args) {
try {
return queryRunner.update(sql,args);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}
public static <T> List<T> queryList(Class<T> clazz, String sql, Object...args){
try {
return (List<T>) queryRunner.query(sql, new BeanListHandler(clazz),args);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
public static <T> T queryOne(Class<T> clazz, String sql, Object...args){
try {
return (T) queryRunner.query(sql, new BeanHandler(clazz),args);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
}