数据库连接池和DBUtils
数据库连接池
what
: 管理连接对象的。
: 数据库连接池断开后,不在进行对对象的销毁,存放在数据库连接池中。
: 应用App不需要在进行创建和断开连接对象而是交给数据连接池管理。
:使用数据库连接池管理对象,减少了数据库连接对象的创建与销毁,提高了数据库的访问效率。
:数据库连接技术:由sun公司来制定这套数据库连接池的规范(数据库连接池的接口),让不同的数据库厂商根据这套规范来编写实现这套接口的技术,主要是DataSource接口。
why(为什莫使用)
当使用jdbc连接数据库的时候,当有1000的用户,你就要建立1000会连接对象和销毁对象,这样会使数据库访问效率大大降低。
两者之间的图
常用的数据源
C3P0数据源和DBCP数据源
数据库连接池中的基本参数
- 初始化大小:数据库连接池中初始的连接对象大小。
- 最大连接数: 数据库库连接池中最大的连接对象的个数。
- 最大等待时间: 用户访问数据库连接池中的对象使的最大的等待时间。
- 最大空闲连接: 用户访问数据库连接池中对象的时候,访问区域稳定的时候,最大的连接对象空闲的个数。
- 最小空闲连接:用户访问数据库连接池中对象的时候,访问趋于峰值的时候,连接池中允许剩余的最小的连接对象。
接口
- 数据源中主要使用 DataSource接口,
- 在DBCP数据源中,使用BasicDataSoure接口,它实现了DataSource这个接口。
- 在DBCP数据源中,如果使用配置文件,使用BasicDataSourceFactory这个接口,使用createDataSourec()创建数据连接池对象。
DBCP数据源连接池
DataBase Connection Pool
需要导入的jar包,common-dbcp-.jar; commons-pool.jar.
使用的接口
- BasicDataSource
- BasicDataSourceFactory
DBCP数据源普通使用
过程
- 导入JAR包
- 编写Demo类,使用BasicDataSourc类,将四个参数封装进去,DriveClassName,Url,UserName,PassWord.初始化连接数,最大,最小连接数。
- 通过使用getConnetion()方法建立连接。
使用
Demo文件
public class Demo {
public static DataSource ds = null;
static {
//使用DataSource接口获取对象
BasicDataSource dataSource = new BasicDataSource();
//为数据源配置四个参数
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/yun6");
dataSource.setUsername("root");
dataSource.setPassword("root");
//为数据库连接池配置参数
dataSource.setInitialSize(5);
dataSource.setMaxActive(10);
ds = dataSource;
}
public static void main(String[] args) throws SQLException {
//建立连接
Connection connection = ds.getConnection();
//拿到它的元数据
DatabaseMetaData metaData = connection.getMetaData();
//输出元数据中的数据
System.out.println( metaData.getDriverName());;
System.out.println(metaData.getUserName());;
System.out.println(metaData.getURL());
}
}
DBCP配置文件的使用
过程
- 编写basicDataSource.properties文件,将连接对象的属性配置进去。
- 编写DbcpDemo文件,将配置文件变成输入流的形式。通过配置文件的实例去加载输入流。
- 通过BasicDataSourceFactory.createDataSource(配置文件实例)方法。得到数据源对象。
- 就可以通过getConnection()方法得到连接对象。
使用
DbcpDemo文件
public class DbcpDemo {
public static DataSource ds = null;
static {
//创建加载配置文件
Properties properties = new Properties();
//类的加载器,获取配置文件的输入流
ClassLoader classLoader = new DbcpDemo().getClass().getClassLoader();
InputStream stream = classLoader.getResourceAsStream("basicDataSource.properties");
try {
//加载配置文件的输入流
properties.load(stream);
//通过配置文件,创建数据源对象
ds = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
//建立连接
Connection connection = ds.getConnection();
//拿到它的元数据
DatabaseMetaData metaData = connection.getMetaData();
//输出元数据中的数据
System.out.println( metaData.getDriverName());;
System.out.println(metaData.getUserName());;
System.out.println(metaData.getURL());
}
}
BasicDataSource.properties文件
在这里插入 #连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/yun6
username=root
password=root
#初始化连接
initialSize=5
#最大连接数量
maxActive=10
#最大空闲连接
maxIdle=10代码片
C3P0数据源
- 性能更加优越,对后期的数据框架hibernate提供支持。
- jar包: c3p0-0.9.1.2.jar
C3P0数据源使用的接口
- ComboPooledDataSource接口
C3P0数据源的普通使用
过程
- 创建C3P0Demo文件
- 创建ComboPooledDataSource的实例,
- 将数据源的参数(4个基本的) 数据连接池基本的配置
- 通过getConnetion()建立连接。
使用
public class C3p0Demo {
public static DataSource ds = null;
static {
// 初始化C3P0数据源
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
try {
//设置连接数据库需要的配置信息
comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
comboPooledDataSource.setUser("root");
comboPooledDataSource.setPassword("root");
comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/yun6");
// 设置连接池的参数
comboPooledDataSource.setInitialPoolSize(5);
comboPooledDataSource.setMaxPoolSize(10);
ds = comboPooledDataSource;
} catch (PropertyVetoException e) {
}
}
public static void main(String[] args) throws SQLException {
// 获取数据库连接对象
System.out.println(ds.getConnection());
}
}
C3P0数据库配置文件使用
过程
- 编写配置文件c3p0-config.xml
- 编写C3p0XmlDemo,ComboPooledDataSource的实例,配置文件通过构造方法自动加载,但配置名必须使这个配置文件的名。
- 如果加载自己定义的配置文件命名的,实例化的时候调用
使用
- 配置文件的名称只能使这个名称:c3p0-config.xml
- 这个配置文件中有默认的配置
- 还可以自己配置, 调用的使用使用“自己命名的”
- ComboPooledDataSource itcast = new ComboPooledDataSource(“itcast”);
c3p0-config.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/yun6
</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="checkoutTimeout">30000</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>
<named-config name="itcast">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/yun6
</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">15</property>
</named-config>
</c3p0-config>
C3p0XmlDemo文件
public class C3p0XmlDemo {
public static DataSource ds = null;
static {
// 使用c3p0-config.xml配置文件中的named-config节点中name属性的值
//在构造方法中加载配置文件c3p0-config.xml。所以它的名字必须是c3p0-config.xml
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
ds = comboPooledDataSource;
}
public static void main(String[] args) throws SQLException {
System.out.println(ds.getConnection());
}
}
C3p0XmlDemo1文件
public class C3p0XmlDemo1 {
private static DataSource da = null;
static {
ComboPooledDataSource itcast = new ComboPooledDataSource("itcast");
da = itcast;
}
public static void main(String[] args) throws SQLException {
System.out.println(da.getConnection());
}
}
DBUtils工具
what
- DBUtils是commons组件中的一员,是对jdbc的简单的封装,减少对操作数据的代码
- jar包: commons-dbutils.jar
接口
- QueryRuner接口
- ResultSetHandler接口
RunnerQuery类
What
runnerQuery接口是DBUtils的核心类,减少操作数据库代码的操作量,主要是jdbc代码进行封装,通常与ResultSetHandler接口配合使用。(对Connection,sql语句,Statement,prepareStatement,ResultSet ,param等进行封装)
方法
- query():执行select
- update():执行insert into,update, delete。
ResultSetHandler接口
- 用于处理结果集,将结果集中封装的对象转换成我们需要的javaBean对象或集合。
接口的实现类
- BeanHandler(): 将结果集中的第一行的数据转换成javaBean的对象
- BeanListHandler(): 将结果集中的第一行的数据转换成javaBean的对象,封装到集合中。
- ScacrHandler():将结果集中数据转换成一个对象,也就是一行一列对应的那个元素。
DBUtils的代码过程
- user类(处理结果集的时候,会转化为javabean对象,user类就是一个javaBean)
- JDBCUtils(将数据库驱动,配置参数,释放资源封装到这个类中)
- BaseDao类:相当与编写了RuuerQuery中的query()方法,
- 分别写了三种结果集的三种实现方法
DBUtils的代码实现
User类
public class User {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
JDBCUtils类:(将数据库驱动,配置参数,释放资源封装到这个类中)
public class JDBCUtils {
// 加载驱动,并建立数据库连接
public static Connection getConnection() throws SQLException,
ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/YUN6";
String username = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, username,
password);
return conn;
}
// 关闭数据库连接,释放资源
public static void release(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static void release(ResultSet rs, Statement stmt,
Connection conn){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
release(stmt, conn);
}
}
BaseDao类:相当与编写了RuuerQuery中的query()方法,
public class BaseDao {
// 优化查询
public static Object query(String sql, ResultSetHandler<?> rsh,
Object... params) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 获得连接
conn = JDBCUtils.getConnection();
// 预编译sql
pstmt = conn.prepareStatement(sql);
// 将参数设置进去
for (int i = 0; params != null && i < params.length; i++)
{
pstmt.setObject(i + 1, params[i]);
}
// 发送sql
rs = pstmt.executeQuery();
// 让调用者去实现对结果集的处理
Object obj = rsh.handle(rs);
return obj;
} catch (Exception e) {
e.printStackTrace();
}finally {
// 释放资源
JDBCUtils.release(rs, pstmt, conn);
}
return rs;
}
}
BandHandler: 随结果集进行处理
public class ResultSetTest1 {
public static void testBeanHandler() throws SQLException {
BaseDao baseDao = new BaseDao();
String sql = " select * form user where id = ?";
User user = (User) baseDao.query(sql, new BeanHandler(User.class), 1);
System.out.println("id为一的Uesr对象的name值为"+user.getName());
}
public static void main(String[] args) throws SQLException {
testBeanHandler();
}
}
BandListHandler: 随结果集进行处理
public class ResultSetTest2 {
public static void testBeanListHandler() throws SQLException {
BaseDao baseDao = new BaseDao();
String sql = " select * form user where ";
ArrayList<User> user = (ArrayList<User>) baseDao.query(sql, new BeanListHandler(User.class));
for(int i = 0;i < user.size();i++){
System.out.println(user.get(i).getName());
}
}
public static void main(String[] args) throws SQLException {
testBeanListHandler();
}
}
ScalarHandler: 随结果集进行处理
public class ResultSetTest3 {
public static void testScalarHandler() throws SQLException {
BaseDao baseDao = new BaseDao();
String sql = " select * form user where id = ?";
Object name = baseDao.query(sql, new ScalarHandler("name"), 1);
System.out.println(name);
}
public static void main(String[] args) throws SQLException {
testScalarHandler();
}
}