【聲明】
歡迎轉載,但請保留文章原始出處→_→
生命壹號:http://www.cnblogs.com/smyhvae/
文章來源:http://www.cnblogs.com/smyhvae/p/4085684.html
聯系方式:smyhvae@163.com
【正文】
這一周狀態不太好,連續打了幾天的點滴,所以博客中斷了一個星期,現在繼續。
我們在之前的幾篇文章中學習了JDBC對數據庫的增刪改查。其實在實際開發中,一般都是使用第三方工具類,但是只有將之前的基礎學習好了,在使用開源工具的時才能得心應手。如果對JDBC基礎不太清楚,或者對本文看不太懂,建議先回顧一下本人之前的幾篇和“MySQL數據庫學習筆記”相關的文章。但是不管怎樣,今後如果用到了數據庫的增刪改查,肯定是這篇文章中的代碼用的最多。
一、DbUtils簡介:
DBUtils是apache下的一個小巧的JDBC輕量級封裝的工具包,其最核心的特性是結果集的封裝,可以直接將查詢出來的結果集封裝成JavaBean,這就為我們做了最枯燥乏味、最容易出錯的一大部分工作。
下載地址:http://commons.apache.org/proper/commons-dbutils/download_dbutils.cgi
DbUtils中的核心的類是QueryRunner類。來看一下裡面的核心方法:
更新操作:
runner.update("delete from user where userName=?","用戶名");
int rowEffects = runner.update("insert into user(userName,password,comment)values(?,?,?)", "用戶名","密碼","備注");
查詢操作:
//返回bean
User user = runner.query("select * from user where userId=?",1,new BeanHandler<User>(User.class));
//返回beanlist
System.out.println("返回BeanList結果......");
List<User> beanListResult =runner.query("select * from user",new BeanListHandler(User.class));
//返回一個值
Object increaseId=runner.query("select last_insert_id()", new ScalarHandler());
三、代碼實現:
下面來看一下DbUtils是怎麼用的。先來看一下整個工程的文件結構:
也就是在這裡用到了DbUtils工具,避免了自己寫很多代碼)
步驟如下:
首先創建數據庫表:person。字段:id,name,age,description。建表的命令如下:
CREATE TABLE person( id int primary key auto_increment, name varchar(20), age int(2), description varchar(100) );
然後往表中填入一些簡單地數據,供稍後查詢。最終效果如下:
mysql-connector-java-5.1.33-bin.jar和剛剛下載好的commons-dbutils-1.6.jar添加到工程的Build path中。(如果不想去官網下載,可以在本文末尾的工程文件中找到)
(1)先新建一個DBUtils工具類:(package com.util.db)
1 package com.util.db;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.sql.Statement;
8 import java.util.ResourceBundle;
9
10 /**
11 * 數據庫操作工具類
12 *
13 * @author lamp
14 *
15 */
16 public class DBUtils {
17
18 // 數據庫連接地址
19 public static String URL;
20 // 用戶名
21 public static String USERNAME;
22 // 密碼
23 public static String PASSWORD;
24 // mysql的驅動類
25 public static String DRIVER;
26
27 private static ResourceBundle rb = ResourceBundle.getBundle("com.util.db.db-config");
28
29 private DBUtils() {
30 }
31
32 // 使用靜態塊加載驅動程序
33 static {
34 URL = rb.getString("jdbc.url");
35 USERNAME = rb.getString("jdbc.username");
36 PASSWORD = rb.getString("jdbc.password");
37 DRIVER = rb.getString("jdbc.driver");
38 try {
39 Class.forName(DRIVER);
40 } catch (ClassNotFoundException e) {
41 e.printStackTrace();
42 }
43 }
44
45 // 定義一個獲取數據庫連接的方法
46 public static Connection getConnection() {
47 Connection conn = null;
48 try {
49 conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
50 } catch (SQLException e) {
51 e.printStackTrace();
52 System.out.println("獲取連接失敗");
53 }
54 return conn;
55 }
56
57 // 關閉數據庫連接
58 public static void close(ResultSet rs, Statement stat, Connection conn) {
59 try {
60 if (rs != null)
61 rs.close();
62 if (stat != null)
63 stat.close();
64 if (conn != null)
65 conn.close();
66 } catch (SQLException e) {
67 e.printStackTrace();
68 }
69 }
70
71 }
注意:27行中,注意獲取屬性文件的包名是否正確。稍後會定義這個屬性文件。
29行:既然是工具類,一般不要實例化,此時可以采用單例設計模式,或者將構造方法私有化。
27行:很明顯可以看到,我們是將連接數據庫的URL、用戶名,密碼等信息編寫在一個屬性文件(jdbc.properties)中,稍後再來定義這個屬性文件。
32行:為避免重復代碼,使用靜態代碼塊:只會在類加載的時候執行一次。
45行:定義一個獲取數據庫連接的方法
57行:關閉數據庫連接
(2)接下來新建一個屬性文件,new-->file,命名為:db-config.properties,代碼如下:
jdbc.url=jdbc:mysql://localhost:3306/jdbcdb jdbc.username=root jdbc.password=smyh jdbc.driver=com.mysql.jdbc.Driver
以後如果需要修改配置信息,只需要在這裡改就行了。注意在上面的DBUtils類中是怎麼來調用這個配置信息的。
(3)新建文件,定義好Person類:(package com.vae.domain)
1 package com.vae.domain;
2
3 public class Person {
4 private int id;
5 private String name;
6 private int age;
7 private String description;
8
9 public int getId() {
10 return id;
11 }
12
13 public void setId(int id) {
14 this.id = id;
15 }
16
17 public String getName() {
18 return name;
19 }
20
21 public void setName(String name) {
22 this.name = name;
23 }
24
25 public int getAge() {
26 return age;
27 }
28
29 public void setAge(int age) {
30 this.age = age;
31 }
32
33 public String getDescription() {
34 return description;
35 }
36
37 public void setDescription(String description) {
38 this.description = description;
39 }
40
41 public Person(int id, String name, int age, String description) {
42 super();
43 this.id = id;
44 this.name = name;
45 this.age = age;
46 this.description = description;
47 }
48
49 public Person(String name, int age, String description) {
50 super();
51 this.name = name;
52 this.age = age;
53 this.description = description;
54 }
55
56 public Person() {
57 super();
58 // TODO Auto-generated constructor stub
59 }
60
61 @Override
62 public String toString() {
63 return "Person [id=" + id + ", name=" + name + ", age=" + age
64 + ", description=" + description + "]";
65 }
66
67 }
這個Person類就是領域模型,表示是對它進行增刪改查。
緊接著定義PersonDao接口:專門對Person類進行操作(例如增刪改查)的接口(package com.vae.dao)
注意:是定義接口,不是定義類。代碼如下:
1 package com.vae.dao;
2
3 import java.sql.SQLException;
4 import java.util.List;
5
6 import com.vae.domain.Person;
7
8 public interface PersonDao {
9 // 添加方法
10 public void add(Person p) throws SQLException;
11
12 // 更新方法
13 public void update(Person p) throws SQLException;
14
15 // 刪除方法
16 public void delete(int id) throws SQLException;
17
18 // 查找方法
19 public Person findById(int id) throws SQLException;
20
21 // 查找所有
22 public List<Person> findAll() throws SQLException;
23
24 // 查詢有幾條記錄
25 public long personCount() throws SQLException;
26
27 }
(4)然後,定義PeronDaoImpl實現類 ,實現上面的PeronDao接口(package com.vae.dao)
1 package com.vae.dao;
2
3 import java.sql.SQLException;
4 import java.util.List;
5
6 import org.apache.commons.dbutils.QueryRunner;
7 import org.apache.commons.dbutils.handlers.BeanHandler;
8 import org.apache.commons.dbutils.handlers.BeanListHandler;
9 import org.apache.commons.dbutils.handlers.ScalarHandler;
10
11 import com.util.db.DBUtils;
12 import com.vae.domain.Person;
13
14 public class PersonDaoImpl implements PersonDao {
15 private QueryRunner runner = null;//查詢運行器
16 public PersonDaoImpl(){
17 runner = new QueryRunner();
18 }
19
20 //方法:向數據庫中添加一條記錄
21 @Override
22 public void add(Person p) throws SQLException {
23 String sql = "insert into person(name,age,description)values(?,?,?)";
24 runner.update(DBUtils.getConnection(), sql, p.getName(), p.getAge(),p.getDescription());
25 }
26
27 //方法:根據id向數據庫中修改某條記錄
28 @Override
29 public void update(Person p) throws SQLException {
30 String sql = "update person set name=?,age=?,description=? where id=?";
31 runner.update(DBUtils.getConnection(), sql, p.getName(),p.getAge(),p.getDescription(),p.getId());
32 }
33
34 //方法:根據id刪除數據庫中的某條記錄
35 @Override
36 public void delete(int id) throws SQLException {
37 String sql = "delete from person where id=?";
38 runner.update(DBUtils.getConnection(), sql, id);
39 }
40
41
42 //方法:使用BeanHandler查詢一個對象
43 @Override
44 public Person findById(int id) throws SQLException {
45 String sql = "select name,age,description from person where id=?";
46 Person p = runner.query(DBUtils.getConnection(), sql, new BeanHandler<Person>(Person.class),id);
47 return p;
48 }
49
50 //方法:使用BeanListHandler查詢所有對象
51 @Override
52 public List<Person> findAll() throws SQLException {
53 String sql = "select name,age,description from person";
54 List<Person> persons = runner.query(DBUtils.getConnection(), sql, new BeanListHandler<Person>(Person.class));
55 return persons;
56 }
57
58 //方法:使用ScalarHandler查詢一共有幾條記錄
59 @Override
60 public long personCount()throws SQLException{
61 String sql = "select count(id) from person";
62 return runner.query(DBUtils.getConnection(),sql, new ScalarHandler<Long>());
63 }
64
65 }
核心代碼:15行、17行、24行、31行、38行、46行、54行、62行。
(5)新建一個測試類Test.java(package com.vae.test)
1 package com.vae.test;
2
3 import java.sql.SQLException;
4 import java.util.List;
5
6 import com.vae.dao.PersonDao;
7 import com.vae.dao.PersonDaoImpl;
8 import com.vae.domain.Person;
9
10 public class Test {
11
12 public static void main(String[] args) throws SQLException {
13 PersonDao dao = new PersonDaoImpl();
14
15 //dao.add(new Person("生命三號",22,"我是通過Java命令而增加的記錄"));
16
17 //dao.update(new Person(1,"生命壹號",23,"我是通過Java命令而修改的記錄"));
18
19 //dao.delete(4);
20
21 //Person p = dao.findById(1);
22 //System.out.println(p);
23
24 //List<Person> persons = dao.findAll();
25 //System.out.println(persons);
26
27 long count = dao.personCount();
28 System.out.println(count);
29 }
30
31 }
經測試,上述15至28行的代碼都能運行。
例如,當執行第21至22代碼時,後台輸出如下:

當執行第24至25代碼時,後台輸出如下:

當執行第27至28代碼時,後台輸出如下:

【工程文件】
鏈接:http://pan.baidu.com/s/1qWqKreO
密碼:9wed