DbUtils框架
一.DbUtils框架概述
1.DbUtils
- 为了更加简单且高效地使用JDBC,Apache组织提供了数据库操作工具类commons-dbutils,该工具可以自动完成:创建连接、封装结果、释放资源。
- DbUtils对JDBC进行了封装,可简化JDBC的编码工作量(例:DbUtils在查询数据时可把结果转换成List,Array,Set等集合)。
2.DbUtils下载官网
3.DbUtils三大核心
(1)DbUtils工具类
(2)ResultSetHandler接口
(3)QueryRunner类
二.DbUtils相关jar包
- mysql-connector-java-5.0.8-bin.jar
- commons-dbutils-1.4.jar
- c3p0-0.9.1.2.jar
三.DbUtils三大核心方法
1.DbUtils工具类
方法 |
方法描述 |
public static boolean loadDriver(java.lang.String driverClassName) |
该方法用于方装载并注册JDBC驱动程序,如果成功就返回true。使用该方法,不需要捕捉ClassNotFoundException |
public static void close(Connection conn,Statement stmt, ResultSet rs) throws java.sql.SQLException |
该类方法用于关闭Connection、Statement和ResultSe |
public static void closeQuietly(Connection conn,Statement stmt, ResultSet rs): |
该类方法不仅能在Connection、Statement和ResultSet为NULL情况下避免关闭,还能隐藏一些在程序中抛出的SQLEeception |
public static void commitAndCloseQuietly(Connection conn) |
该方法用于提交事务并关闭连接,而且在关闭连接时不抛出SQL异常。 |
public static void rollbackAndCloseQuietly(Connection conn) |
该方法用于回滚事务并关闭连接,而且在关闭连接时不抛出SQL异常。 |
2.ResultSetHandler接口
实现类 |
实现类描述 |
BeanHandler |
将结果集中的第一行数据封装到一个对应的JavaBean实例中。 |
BeanListHandler |
将结果集中的每一行数据都封装到一个对应的JavaBean实例中,再存放到List里 |
ArrayHandler |
把结果集中的第一行数据转成对象数组 |
ArrayListHandler |
把结果集中的每一行数据都转成一个数组存放到List中 |
ColumnListHandler |
将结果集中某一列的数据存放到List中 |
KeyedHandler(name) |
将结果集中的每一行数据都封装到一个Map<列名,列值>里,再把这些map再存到一个map里,其key为指定的key |
MapHandler |
将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值 |
MapListHandler |
将结果集中的每一行数据都封装到一个Map里,然后再存放到List |
ScalarHandler |
将结果集中某一条记录的其中某一列的数据存储成Object对象;常用于获取聚合函数的值 |
3.QueryRunner类
方法 |
方法描述 |
QueryRunner() |
采用该方法创建QueryRunner时数据库的事务可由我们自己手动控制。 正因为该构造方法无参,所以在调用该对象的query、update、等方法时需要传入参数Connection。 利用QueryRunner的无参构造函数即QueryRunner( )创建QueryRunner执行数据库操作后需要手动关闭数据库连接Connection |
public Object query(Connection conn, String sql, Object[] params, ResultSetHandler rsh) throws SQLException |
该方法用于执行查询,在该查询中Object数组里的每个值被用来作为查询语句的置换参数。该方法会自行处理PreparedStatement和ResultSet的创建和关闭。 |
public Object query(String sql, Object[] params, ResultSetHandler rsh) throws SQLException |
该方法与上面的这个方法基本一样;不同的是它不用传入参数Connection |
public Object query(Connection conn, String sql, ResultSetHandler rsh) throws SQLException |
该方法与上面的两个方法基本一样,它用于执行一个不需要置换参数的查询操作。 |
public int update(Connection conn, String sql, Object[] params) throws SQLException |
该方法用于执行更新操作(例如:增加、删除、更新),在该查询中Object数组里的每个元素值被用来作为更新语句的置换参数 |
public int update(Connection conn, String sql) throws SQLException |
该方法与上面的方法基本一样,用来执行一个不需要置换参数的更新操作。 |
public int update(String sql) throws SQLException |
该方法与上面的方法基本一样,用来执行一个不需要置换参数和不指定Connection的更新操作。 |
四.DbUtils简单封装
sql
复制代码
package cn.com.demo06;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.apache.commons.dbutils.DbUtils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DBUtils {
//创建数据库连接池
private static DataSource dataSource = new ComboPooledDataSource();
//获取数据库连接池
public static DataSource getDataSource() {
return dataSource;
}
//创建连接
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("获取数据库连接失败");
}
}
//释放连接
public static void releaseConnection(Connection connection, Statement statement, ResultSet resultSet) {
DbUtils.closeQuietly(connection, statement, resultSet);
}
}
五.DbUtils简单使用示例
1.创建表
SQL
复制代码
-- 若存在数据库mydb则删除
DROP DATABASE IF EXISTS mydb;
-- 创建数据库mydb
CREATE DATABASE mydb;
-- 选择数据库mydb
USE mydb;
-- 创建表
CREATE TABLE membershipcard (
id int primary key auto_increment,
username varchar(40),
password varchar(40),
email varchar(40),
birthday date
);
-- 插入数据
INSERT INTO membershipcard (username,password,email,birthday) VALUES ("lili","lili123","lili@sina.com","1999-08-14");
INSERT INTO membershipcard (username,password,email,birthday) VALUES ("fafa","fafa456","fafa@sohu.com","1998-07-15");
INSERT INTO membershipcard (username,password,email,birthday) VALUES ("guigui","guigui333","guigui@sina.com","1997-06-16");
INSERT INTO membershipcard (username,password,email,birthday) VALUES ("bing","bing666","bing@sohu.com","1996-05-17");
2.实体类
Java
复制代码
package cn.com.demo06;
import java.util.Date;
public class MembershipCard {
private int id;
private String username;
private String password;
private String email;
private Date birthday;
public MembershipCard() {
}
public MembershipCard(int id, String username, String password, String email, Date birthday) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "MembershipCard [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email
+ ", birthday=" + birthday + "]";
}
}
3.DbUtils实现增删改查
Java
复制代码
package cn.com.demo06;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
public class TestDBUtils1 {
public static void main(String[] args) {
try {
TestDBUtils1 demo = new TestDBUtils1();
demo.testSelectAll();
} catch (Exception e) {
e.printStackTrace();
}
}
+
// 插入数据
public void testInsert() throws SQLException {
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
Date birthday = Date.valueOf("1997-07-01");
String sql = "insert into membershipcard(username,password,email,birthday) values(?,?,?,?)";
Object params[] = { "huhu", "huhu777", "huhu@sina.com", birthday };
qr.update(sql, params);
}
// 更新数据
public void testUpdate() throws SQLException {
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "update membershipcard set password=? where username=?";
Object params[] = { "888888", "huhu" };
qr.update(sql, params);
}
// 删除数据
public void testDelete() throws SQLException {
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "delete from membershipcard where username=?";
Object params[] = { "huhu" };
qr.update(sql, params);
}
// 查询单个数据
public void testSelect() throws SQLException {
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "select * from membershipcard where username=?";
Object params[] = { "lili" };
BeanHandler<MembershipCard> beanHandler=new BeanHandler<>(MembershipCard.class);
MembershipCard membershipCard=qr.query(sql, beanHandler, params);
System.out.println(membershipCard);
}
// 查询所有数据
public void testSelectAll() throws SQLException {
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql="select * from membershipcard";
BeanListHandler<MembershipCard> beanListHandler = new BeanListHandler<MembershipCard>(MembershipCard.class);
List<MembershipCard> list = qr.query(sql, beanListHandler);
for (MembershipCard membershipCard : list) {
System.out.println(membershipCard);
}
}
}
4.DbUtils实现查询
Java
复制代码
package cn.com.demo06;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
public class TestDBUtils2 {
public static void main(String[] args) {
try {
TestDBUtils2 demo = new TestDBUtils2();
demo.testBeanListHandler();
} catch (Exception e) {
e.printStackTrace();
}
}
//BeanHandler
public void testBeanHandler() throws SQLException {
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "select * from membershipcard where username=?";
Object params[] = { "lili" };
BeanHandler<MembershipCard> beanHandler = new BeanHandler<>(MembershipCard.class);
MembershipCard membershipCard = qr.query(sql, beanHandler, params);
System.out.println(membershipCard);
}
//BeanListHandler
public void testBeanListHandler() throws SQLException {
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "select * from membershipcard";
BeanListHandler<MembershipCard> beanListHandler = new BeanListHandler<MembershipCard>(MembershipCard.class);
List<MembershipCard> list = qr.query(sql, beanListHandler);
for (MembershipCard membershipCard : list) {
System.out.println(membershipCard);
}
}
//ArrayHandler
public void testArrayHandler() throws SQLException{
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "select * from membershipcard";
ArrayHandler arrayHandler=new ArrayHandler();
Object[] resultArray = qr.query(sql, arrayHandler);
for(Object o:resultArray) {
System.out.println(o);
}
System.out.println(Arrays.asList(resultArray));
}
//ArrayListHandler
public void testArrayListHandler() throws SQLException {
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "select * from membershipcard";
ArrayListHandler arrayListHandler=new ArrayListHandler();
List<Object[]> list=qr.query(sql, arrayListHandler);
for(Object[] obj:list) {
System.out.println(Arrays.asList(obj));
}
}
//ColumnListHandler
public void testColumnListHandler() throws SQLException {
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "select * from membershipcard";
ColumnListHandler columnListHandler=new ColumnListHandler("username");
List<Object> list = qr.query(sql, columnListHandler);
for(Object obj:list) {
System.out.println(obj);
}
}
//KeyedHandler
public void testKeyedHandler() throws SQLException {
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "select * from membershipcard";
KeyedHandler keyedHandler = new KeyedHandler("username");
Map<Object, Map<String, Object>> resultMap = qr.query(sql, keyedHandler);
Set<Object> resultMapKeySet = resultMap.keySet();
Iterator<Object> resultMapIterator = resultMapKeySet.iterator();
while(resultMapIterator.hasNext()) {
Object resultMapKey = resultMapIterator.next();
System.out.println("key="+resultMapKey);
Map<String, Object> innerMap = resultMap.get(resultMapKey);
Set<String> innerMapKeySet = innerMap.keySet();
Iterator<String> innerMapIterator = innerMapKeySet.iterator();
while(innerMapIterator.hasNext()) {
String innerMapKey = innerMapIterator.next();
Object innerMapValue = innerMap.get(innerMapKey);
System.out.println(innerMapKey+"="+innerMapValue);
}
System.out.println();
}
}
//MapHandler
public void testMapHandler() throws SQLException{
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "select * from membershipcard";
MapHandler mapHandler=new MapHandler();
Map<String, Object> map = qr.query(sql, mapHandler);
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
while(iterator.hasNext()) {
String key = iterator.next();
Object value = map.get(key);
System.out.println(key+"="+value);
}
}
//测试MapListHandler
public void testMapListHandler() throws SQLException{
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "select * from membershipcard";
MapListHandler mapListHandler=new MapListHandler();
List<Map<String,Object>> list = qr.query(sql, mapListHandler);
for(int i=0;i<list.size();i++) {
Map<String, Object> map = list.get(i);
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
while(iterator.hasNext()) {
String key = iterator.next();
Object value = map.get(key);
System.out.println(key+"="+value);
}
System.out.println();
}
}
//ScalarHandler
public void testScalarHandler() throws SQLException{
QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
String sql = "select count(*) from membershipcard";
ScalarHandler scalarHandler=new ScalarHandler();
String result = qr.query(sql,scalarHandler).toString();
System.out.println(Integer.valueOf(result));
}
}
六.DbUtils处理事务
- DbUtils常在Service层获得连接Connection得以保证涉及事务操作的Connection对象为同一个
1.创建表
SQL
复制代码
DROP DATABASE IF EXISTS mydb;
-- 创建数据库
CREATE DATABASE mydb;
-- 选择数据库mydb
USE mydb;
-- 创建account表
CREATE TABLE account(
id INT primary key auto_increment,
name VARCHAR(40),
money FLOAT
);
-- 插入数据
INSERT INTO account(name, money) VALUES ('A',1000);
INSERT INTO account(name, money) VALUES ('B',1000);
2.AccountDao
Java
复制代码
package cn.com.demo06;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
public class AccountDao {
//转出别人
public void outMoney(Connection connection, String from, float money) {
QueryRunner qr = new QueryRunner();
try {
String sql = "update account set money = money - ? where name = ?";
Object params[] = {money,from};
qr.update(connection, sql, params);
} catch (SQLException e) {
e.printStackTrace();
}
}
//转入自己
public void inMoney(Connection connection, String to, float money) {
QueryRunner qr = new QueryRunner();
try {
String sql = "update account set money = money + ? where name = ?";
Object params[] = {money,to};
qr.update(connection, sql,params);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3.AccountService
Java
复制代码
package cn.com.demo06;
import java.sql.Connection;
import org.apache.commons.dbutils.DbUtils;
public class AccountService {
public void transfer(String from, String to, float money) {
AccountDao accountDao = new AccountDao();
Connection connection = null;
try {
//获得连接
connection = DBUtils.getConnection();
//设置事务不自动提交
connection.setAutoCommit(false);
accountDao.outMoney(connection,from,money);
//模拟异常
//int error = 1/0 ;
accountDao.inMoney(connection,to,money);
//提交事务并安静地关闭连接
DbUtils.commitAndCloseQuietly(connection);
} catch (Exception e) {
//异常出现时,回滚事务并安静地关闭连接
DbUtils.rollbackAndCloseQuietly(connection);
//e.printStackTrace();
}
}
}
4.测试DbUtils事务处理
Java
复制代码
package cn.com.demo06;
public class TestDBUtils {
public static void main(String[] args) {
AccountService accountService=new AccountService();
accountService.transfer("A", "B", 200);
System.out.println("transfer 结束");
}
}
七.DbUtils实用封装
1.创建数据库及表
sql
复制代码
-- 若存在数据库mydb则删除
DROP DATABASE IF EXISTS mydb;
-- 创建数据库mydb
CREATE DATABASE mydb;
-- 选择数据库mydb
USE mydb;
-- 创建表
CREATE TABLE user (
id int primary key auto_increment,
username varchar(40),
password varchar(40),
email varchar(40),
birthday date
);
-- 插入数据
INSERT INTO user (username,password,email,birthday) VALUES ("lili","lili123","lili@sina.com","1999-08-14");
INSERT INTO user (username,password,email,birthday) VALUES ("fafa","fafa456","fafa@sohu.com","1998-07-15");
INSERT INTO user (username,password,email,birthday) VALUES ("guigui","guigui333","guigui@sina.com","1997-06-16");
INSERT INTO user (username,password,email,birthday) VALUES ("bing","bing666","bing@sohu.com","1996-05-17");
2.编写c3p0-config.xml
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/mydb</property>
<property name="user">root</property>
<property name="password">test</property>
<property name="initialPoolSize">15</property>
<property name="maxIdleTime">40</property>
<property name="maxPoolSize">150</property>
<property name="minPoolSize">20</property>
</default-config>
</c3p0-config>
3.编写User
java
复制代码
package cn.com.demo07;
import java.util.Date;
public class User {
private int id;
private String username;
private String password;
private String email;
private Date birthday;
public User() {
}
public User(int id, String username, String password, String email, Date birthday) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email+ ", birthday=" + birthday + "]";
}
}
4.编写DBUtils
- C3P0连接池的配置文件名称必须为c3p0-config.xml
- 读取配置文件、加载驱动类、创建连接等操作均由连接池自动完成
java
复制代码
package cn.com.demo07;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* 数据库操作工具类
*/
public class DBUtils {
private static DataSource datasource;
static {
try {
datasource = new ComboPooledDataSource();
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取数据库链接
*/
public static Connection getConnection(){
Connection connection = null;
try {
connection = datasource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* 执行更新操作:增加、修改、删除
* @param sql SQL语句
* @param parameters SQL参数
* @return 0失败、1成功
*/
public static Integer executeUpdate(String sql,Object ...parameters){
Connection connection = getConnection();
QueryRunner queryRunner = new QueryRunner();
Integer result = 0;
try {
if(parameters == null){
result = queryRunner.update(connection, sql);
}else{
result = queryRunner.update(connection, sql, parameters);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 执行更新操作:增加、修改、删除
*/
public static Integer executeUpdate(String sql){
Object [] parameters=null;
return executeUpdate(sql, parameters);
}
/**
* 执行查询操作
* @param <T> 实体泛型
* @param sql SQL语句
* @param clazz 实体的Class
* @param parameters SQL参数
* @return 存放Bean的list
*/
public static <T> List<T> executeQuery(String sql,Class<T> clazz,Object ...parameters){
Connection connection = getConnection();
List<T> list = null;
try{
QueryRunner queryRunner = new QueryRunner();
BeanListHandler<T> beanListHandler = new BeanListHandler<T>(clazz);
if(parameters == null){
list = queryRunner.query(connection, sql,beanListHandler);
}else{
list = queryRunner.query(connection, sql,beanListHandler,parameters);
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
/**
* 执行查询操作
*/
public static <T> List<T> executeQuery(String sql,Class<T> clazz){
Object [] parameters=null;
return executeQuery(sql,clazz,parameters);
}
/**
* 查询记录数
*/
public static int getCount(String sql){
Connection connection = getConnection();
QueryRunner queryRunner = new QueryRunner();
Integer count = null;
try {
Long longCount= (Long) queryRunner.query(connection,sql,new ScalarHandler(1));
count = longCount.intValue();
}catch (Exception e){
e.printStackTrace();
}
return count;
}
}
5.编写TestDBUtils
java
复制代码
package cn.com.demo07;
import java.util.List;
public class TestDBUtils {
public static void main(String[] args) {
TestDBUtils test = new TestDBUtils();
List<User> userList1 = test.testQuery1();
for (User user : userList1) {
System.out.println(user);
}
System.out.println("-----------------");
List<User> userList2 = test.testQuery2("lili");
for (User user : userList2) {
System.out.println(user);
}
System.out.println("-----------------");
List<User> userList3 = test.testQuery3("lili", "123456");
for (User user : userList3) {
System.out.println(user);
}
System.out.println("-----------------");
int result = test.testUpdate("lili", "666666", "lili@sohu.com");
if(result>0) {
List<User> userList = test.testQuery1();
for (User user : userList) {
System.out.println(user);
}
}else {
System.out.println("更新用户失败");
}
}
// 查询所有用户
public List<User> testQuery1() {
String sql = "select * from user";
List<User> list = DBUtils.executeQuery(sql, User.class);
return list;
}
// 依据用户名查询用户
public List<User> testQuery2(String username) {
String sql = "select * from user where username=?";
List<User> list = DBUtils.executeQuery(sql, User.class, username);
return list;
}
// 依据用户名和密码查询用户
public List<User> testQuery3(String username, String password) {
String sql = "select * from user where username=? and password=?";
List<User> list = DBUtils.executeQuery(sql, User.class, username, password);
return list;
}
//更新用户
public int testUpdate(String username, String password, String email) {
String sql = "update user set password=? , email=? where username=?";
int result = DBUtils.executeUpdate(sql, password, email, username);
return result;
}
}