DbUtils框架(这是一个耗时耗力的差事)
文章目錄
- 前言
- 一、DbUtils三大核心體現(xiàn)
- 二、DbUtils工具類
- 三、ResultSetHandler接口實現(xiàn)類
- 四、QueryRunner類
- 1.QueryRunner常用的構(gòu)造函數(shù)
- 2.QueryRunner的常用方法
- 五、使用實例
- 1 添加jar包
- 2 在src下創(chuàng)建c3p0的配置文件c3p0-config.xml
- 3 DbUtils簡易封裝
- 4 在數(shù)據(jù)庫中建立會員卡表并插入數(shù)據(jù)
- 5 創(chuàng)建一個MembershipCard類(里面的元素與數(shù)據(jù)庫中的會員卡表字段信息類型相同)
- 6 利用DbUtils實現(xiàn)增刪改查
- 總結(jié)
前言
為更加簡單且高效地使用JDBC,Apache組織提供了數(shù)據(jù)庫操作工具類commons-dbutils。該工具對JDBC進(jìn)行了封裝,可極大地簡化JDBC的編碼工作量。例如:DbUtils在查詢數(shù)據(jù)時可把結(jié)果轉(zhuǎn)換成List,Array,Set等集合,非常便于開發(fā)人員操作。
一、DbUtils三大核心體現(xiàn)
1、DbUtils工具類 該類主要用于關(guān)閉連接、裝載JDBC驅(qū)動程序等等
2、ResultSetHandler接口 該接口及其實現(xiàn)類主要用于處理結(jié)果集
3、QueryRunner類 該類主要用于增,刪,改,查
二、DbUtils工具類
由于這不是Java自帶的工具類,查詢比較麻煩,在這里我就僅僅列舉最常用的吧,如下所示:
代碼如下(DbUtils工具類第一個列舉):
public static boolean loadDriver(java.lang.String driverClassName)該方法用于方裝載并注冊JDBC驅(qū)動程序,如果成功就返回true。使用該方法,不需要捕捉ClassNotFoundException
代碼如下(DbUtils工具類第二個列舉):
public static void close(Connection conn,Statement stmt, ResultSet rs) throws java.sql.SQLException該類方法用于關(guān)閉Connection、Statement和ResultSet
代碼如下(DbUtils工具類第三個列舉):
public static void closeQuietly(Connection conn,Statement stmt, ResultSet rs):該類方法不僅能在Connection、Statement和ResultSet為NULL情況下避免關(guān)閉,還能隱藏一些在程序中拋出的SQLEeception
代碼如下(DbUtils工具類第四個列舉):
public static void commitAndCloseQuietly(Connection conn)該方法用于提交事務(wù)并關(guān)閉連接,而且在關(guān)閉連接時不拋出SQL異常。
代碼如下(DbUtils工具類第五個列舉):
public static void rollbackAndCloseQuietly(Connection conn)該方法用于回滾事務(wù)并關(guān)閉連接,而且在關(guān)閉連接時不拋出SQL異常。
三、ResultSetHandler接口實現(xiàn)類
1、BeanHandler 將結(jié)果集中的第一行數(shù)據(jù)封裝到一個對應(yīng)的JavaBean實例中。
2、BeanListHandler 將結(jié)果集中的每一行數(shù)據(jù)都封裝到一個對應(yīng)的JavaBean實例中,再存放到List里
3、ArrayHandler 把結(jié)果集中的第一行數(shù)據(jù)轉(zhuǎn)成對象數(shù)組
4、ArrayListHandler 把結(jié)果集中的每一行數(shù)據(jù)都轉(zhuǎn)成一個數(shù)組存放到List中
5、ColumnListHandler 將結(jié)果集中某一列的數(shù)據(jù)存放到List中/6、KeyedHandler(name) 將結(jié)果集中的每一行數(shù)據(jù)都封裝到一個Map<列名,列值>里,再把這些map再存到一個map里,其key為指定的key。
6、MapHandler 將結(jié)果集中的第一行數(shù)據(jù)封裝到一個Map里,key是列名,value就是對應(yīng)的值
7、MapListHandler 將結(jié)果集中的每一行數(shù)據(jù)都封裝到一個Map里,然后再存放到List
8、ScalarHandler 將結(jié)果集中某一條記錄的其中某一列的數(shù)據(jù)存儲成Object對象
四、QueryRunner類
1.QueryRunner常用的構(gòu)造函數(shù)
QueryRunner() 采用該方法創(chuàng)建QueryRunner時數(shù)據(jù)庫的事務(wù)可由我們自己手動控制。正因為該構(gòu)造方法無參,所以在調(diào)用該對象的query、update、等方法時需要傳入?yún)?shù)Connection。
QueryRunner(DataSource ds) 采用該方法創(chuàng)建QueryRunner時數(shù)據(jù)庫的事務(wù)由DBUtils自動控制。正因為該構(gòu)造方法傳入了參數(shù)DataSource,所以在調(diào)用該對象的query、update、等方法時無需傳入?yún)?shù)Connection。
2.QueryRunner的常用方法
public Object query(Connection conn, String sql, Object[] params, ResultSetHandler rsh)該方法用于執(zhí)行查詢,在該查詢中Object數(shù)組里的每個值被用來作為查詢語句的置換參數(shù)。該方法會自行處理PreparedStatement和ResultSet的創(chuàng)建和關(guān)閉。
public Object query(String sql, Object[] params, ResultSetHandler rsh)不用傳入?yún)?shù)Connection
public Object query(Connection conn, String sql, ResultSetHandler rsh)該方法與上面的兩個方法基本一樣,它用于執(zhí)行一個不需要置換參數(shù)的查詢操作。
public int update(Connection conn, String sql, Object[] params)該方法用于執(zhí)行更新操作(例如:增加、刪除、更新),在該查詢中Object數(shù)組里的每個元素值被用來作為更新語句的置換參數(shù)。
五、使用實例
1 添加jar包
c3p0-0.9.1.2.jar
commons-dbutils-1.4.jar
mysql-connector-java-5.0.8-bin.jar
導(dǎo)包位置如下:
2 在src下創(chuàng)建c3p0的配置文件c3p0-config.xml
如下圖所示c3p0-config.xml配置的級別與src同級,文件名建議直接復(fù)制
c3p0-config.xml里面的內(nèi)容如下(只需要修改當(dāng)前使用的數(shù)據(jù)庫及數(shù)據(jù)庫的use和password)
<?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/你當(dāng)前使用的數(shù)據(jù)庫名</property><property name="user">使用者名字</property><property name="password">密碼</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 DbUtils簡易封裝
代碼如下(DbUtils工具類):
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource;public class DBUtils {//創(chuàng)建數(shù)據(jù)庫連接池private static DataSource dataSource = new ComboPooledDataSource();//獲取數(shù)據(jù)庫連接池public static DataSource getDataSource() {return dataSource;}//創(chuàng)建連接public static Connection getConnection(){try {return dataSource.getConnection();} catch (SQLException e) {throw new RuntimeException("獲取數(shù)據(jù)庫連接失敗");}}//釋放連接public static void releaseConnection(Connection connection, Statement statement, ResultSet resultSet) {if (resultSet != null) {try {resultSet.close();} catch (Exception e) {e.printStackTrace();}resultSet = null;}if (statement != null) {try {statement.close();} catch (Exception e) {e.printStackTrace();}statement = null;}if (connection != null) {try {connection.close();} catch (Exception e) {e.printStackTrace();}connection = null;}} }4 在數(shù)據(jù)庫中建立會員卡表并插入數(shù)據(jù)
代碼如下(建立會員卡表的MySQL命令):
-- 若存在數(shù)據(jù)庫mydb則刪除 DROP DATABASE IF EXISTS mydb; -- 創(chuàng)建數(shù)據(jù)庫mydb CREATE DATABASE mydb; -- 選擇數(shù)據(jù)庫mydb USE mydb;-- 創(chuàng)建表 CREATE TABLE membershipcard (id int primary key auto_increment, username varchar(40),password varchar(40), email varchar(40), birthday date );-- 插入數(shù)據(jù) INSERT INTO membershipcard (username,password,email,birthday) VALUES ("lili","abc123","lili@sina.com","1999-08-14"); INSERT INTO membershipcard (username,password,email,birthday) VALUES ("koko","efg456","koko@sohu.com","1998-07-15"); INSERT INTO membershipcard (username,password,email,birthday) VALUES ("mbmb","mnb333","mbmb@sina.com","1997-06-16"); INSERT INTO membershipcard (username,password,email,birthday) VALUES ("zxzx","poi666","zxzx@sohu.com","1996-05-17");5 創(chuàng)建一個MembershipCard類(里面的元素與數(shù)據(jù)庫中的會員卡表字段信息類型相同)
代碼如下(MembershipCard類):
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;}@Overridepublic String toString() {return "MembershipCard [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email+ ", birthday=" + birthday + "]";}}6 利用DbUtils實現(xiàn)增刪改查
代碼如下(DbUtils實現(xiàn)增刪改查測試):
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 Test01 {public static void main(String[] args) {Test01 test01 = new Test01();test01.testSelect();// test01.testSelectAll();// test01.testUpdate();// test01.testDelete();// test01.testInsert();}// 插入數(shù)據(jù)public void testInsert() {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[] = { "zsa", "007", "077@sina.com", birthday };try {qr.update(sql, params);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("suc");}// 刪除數(shù)據(jù)public void testDelete() {QueryRunner qr = new QueryRunner(DBUtils.getDataSource());String sql = "delete from membershipcard where username=?";Object[] param = {"zsa"};try {qr.update(sql, param);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 更新數(shù)據(jù)public void testUpdate() {QueryRunner qr = new QueryRunner(DBUtils.getDataSource());String sql = "update membershipcard set password=? where username=?";Object[] param = {"12546","zxzx"};try {qr.update(sql, param);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 查詢所有數(shù)據(jù)public void testSelectAll() {QueryRunner qr = new QueryRunner(DBUtils.getDataSource());String sql = "select * from membershipcard";BeanListHandler<MembershipCard> beanListHandler = new BeanListHandler<>(MembershipCard.class);try {List<MembershipCard> list = qr.query(sql,beanListHandler);for(MembershipCard membershipCard:list) {System.out.println(membershipCard);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 查詢單條數(shù)據(jù)public void testSelect(){QueryRunner qr = new QueryRunner(DBUtils.getDataSource());String sql = "select * from membershipcard where username=?";Object[] param = {"zxzx"};BeanHandler<MembershipCard> beanHandler = new BeanHandler<>(MembershipCard.class);try {MembershipCard query = qr.query(sql,beanHandler , param);System.out.println(query);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}} }查詢單條數(shù)據(jù)測試輸出:
查詢所有數(shù)據(jù)測試輸出:
添加一條數(shù)據(jù)測試輸出:
看看數(shù)據(jù)表中是否真的插入了數(shù)據(jù)
更新一條數(shù)據(jù)測試輸出:
看看數(shù)據(jù)表中是否真的更新了數(shù)據(jù)
刪除一條數(shù)據(jù)測試輸出:
看看數(shù)據(jù)表中是否真的刪除了數(shù)據(jù)
總結(jié)
在該示例中利用DbUtils實現(xiàn)了增刪改查操作。其中,我們可利用BeanHandler將查詢到的一條數(shù)據(jù)轉(zhuǎn)換成與其對應(yīng)的JavaBean;類似地,我們可利用BeanListHandler將查詢到的多條數(shù)據(jù)轉(zhuǎn)換為JavaBean再存放至List集合。
注意:
當(dāng)有數(shù)據(jù)需要插入數(shù)據(jù)表示,導(dǎo)的包應(yīng)該是java.sql這種格式的
總結(jié)
以上是生活随笔為你收集整理的DbUtils框架(这是一个耗时耗力的差事)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机工程学院运动会加油稿50字,运动会
- 下一篇: BUUCTF misc 专题(22)隐藏