MySQL数据库学习笔记(十二)----开源工具DbUtils的使用(数据库的增删改查)

来源:互联网 发布:如何撤销淘宝退款申请 编辑:程序博客网 时间:2024/06/10 09:56

本文并非原创性的文章。

生命壹号:http://www.cnblogs.com/smyhvae/

文章来源:http://www.cnblogs.com/smyhvae/p/4085684.html

【正文】

这一周状态不太好,连续打了几天的点滴,所以博客中断了一个星期,现在继续。

我们在之前的几篇文章中学习了JDBC对数据库的增删改查。其实在实际开发中,一般都是使用第三方工具类,但是只有将之前的基础学习好了,在使用开源工具的时才能得心应手。如果对JDBC基础不太清楚,或者对本文看不太懂,建议先回顾一下本人之前的几篇和“MySQL数据库学习笔记”相关的文章。但是不管怎样,今后如果用到了数据库的增删改查,肯定是这篇文章中的代码用的最多。

一、DbUtils简介:

DBUtils是apache下的一个小巧的JDBC轻量级封装的工具包,其最核心的特性是结果集的封装,可以直接将查询出来的结果集封装成JavaBean,这就为我们做了最枯燥乏味、最容易出错的一大部分工作。

下载地址:http://commons.apache.org/proper/commons-dbutils/download_dbutils.cgi

584c972c-b14a-4354-8f8d-7307900d46c3

下载上图中的红框部分,然后解压。解压之后的文件如下 :

87b4dfbd-98bb-4916-9cf5-69ac5e8994c9

上图中红框部分的文件就是我们所需要的内容。

 

二、核心方法:

DbUtils中的核心的类是QueryRunner类。来看一下里面的核心方法:

更新操作:

runner.update("delete from user where userName=?","用户名");int rowEffects = runner.update("insert into user(userName,password,comment)values(?,?,?)", "用户名","密码","备注");

查询操作:

复制代码
//返回beanUser user = runner.query("select * from user where userId=?",1,new BeanHandler<User>(User.class)); //返回beanlistSystem.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是怎么用的。先来看一下整个工程的文件结构:

91294a25-8f37-4259-a6a8-5daa2954106e

  • DBUtils:初步封装的JDBC工具类;
  • db-config.properties:属性文件,方便修改配置信息;
  • Person类就是领域模型,表示是对它(数据库表)进行增删改查。
  • PersonDao接口:专门对Person类进行操作(例如增删改查)的接口。注:这里不直接写操作类,是因为接口利于维护,可以在这里写上公共的代码。一个领域模型对应一个Dao接口。
  • PeronDaoImpl类:实现上面的PeronDao接口(也就是在这里用到了DbUtils工具,避免了自己写很多代码
  • Test类:测试代码的可用性。

步骤如下:

首先创建数据库表:person。字段:id,name,age,description。建表的命令如下:

CREATE TABLE person(id int primary key auto_increment,name varchar(20),age int(2),description varchar(100)); 

然后往表中填入一些简单地数据,供稍后查询。最终效果如下:

ba506494-5577-41fb-937f-4626b28f7e81

接下来是具体的代码实现:

打开eclipse,新建Java工程DBTest,然后在根目录下新建一个文件夹libs,将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 lamp14  * 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/jdbcdbjdbc.username=rootjdbc.password=smyhjdbc.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 stub59     }60 61     @Override62     public String toString() {63         return "Person [id=" + id + ", name=" + name + ", age=" + age64                 + ", 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     @Override22     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     @Override29     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     @Override36     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     @Override44     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     @Override52     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     @Override60     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代码时,后台输出如下:

639b2653-3143-427a-b83c-69cbdf5968e8

当执行第24至25代码时,后台输出如下:

15ef15d9-44f2-4d3f-8dca-b13153ef54d2

当执行第27至28代码时,后台输出如下:

cc648cee-e982-4eb0-917c-fd310531391c

【工程文件】

链接:http://pan.baidu.com/s/1qWqKreO

密码:9wed



0 0