转自:http://blog.csdn.net/earbao/article/details/44901061
apache DBUtils是java编程中的数据库操作实用工具,小巧简单实用,
1.对于数据表的读操作,他可以把结果转换成List,Array,Set等java集合,便于程序员操作;
2.对于数据表的写操作,也变得很简单(只需写sql语句)
3.可以使用数据源,使用JNDI,数据库连接池等技术来优化性能--重用已经构建好的数据库连接对象,而不像php,asp那样,费时费力的不断重复的构建和析构这样的对象。
DBUtils包括3个包:
org.apache.commons.dbutils
org.apache.commons.dbutils.handlers
org.apache.commons.dbutils.wrappers
DBUtils封装了对JDBC的操作,简化了JDBC操作,可以少写代码。
org.apache.commons.dbutils
DbUtils 关闭链接等操作
QueryRunner 进行查询的操作
org.apache.commons.dbutils.handlers
ArrayHandler :将ResultSet中第一行的数据转化成对象数组
ArrayListHandler将ResultSet中所有的数据转化成List,List中存放的是Object[]
BeanHandler :将ResultSet中第一行的数据转化成类对象
BeanListHandler :将ResultSet中所有的数据转化成List,List中存放的是类对象
ColumnListHandler :将ResultSet中某一列的数据存成List,List中存放的是Object对象
KeyedHandler :将ResultSet中存成映射,key为某一列对应为Map。Map中存放的是数据
MapHandler :将ResultSet中第一行的数据存成Map映射
MapListHandler :将ResultSet中所有的数据存成List。List中存放的是Map
ScalarHandler :将ResultSet中一条记录的其中某一列的数据存成Object
org.apache.commons.dbutils.wrappers
SqlNullCheckedResultSet :对ResultSet进行操作,改版里面的值
StringTrimmedResultSet :去除ResultSet中中字段的左右空格。Trim()
主要方法:
DbUtils类:启动类
ResultSetHandler接口:转换类型接口
MapListHandler类:实现类,把记录转化成List
BeanListHandler类:实现类,把记录转化成List,使记录为JavaBean类型的对象
Qrery Runner类:执行SQL语句的类
Queryrunner.query —————只可以执行select语句。
Queryrunner.update —————只可以接收update,delte,insert语句
BeanHandler ——————返回一个 Bean,结果封装到Bean。只查询第一行。适合根据id查询唯一的一行
BeanListHandler ——————返回List<Bean>所有行,都封装到List,适合于查询多个结果
MapHandler ——————与BeanHandler应,只返回第一行,封装成Map类型 - 也适合于查询一个结果集的 适合于关联查询,且没有匹配的Bean。
MapListHandler ——————与BeanListHandler对应,返回所有,封装成List<Map>类型
ScalarHandler ——————标量- 用于select count(1)|sum|avg|max …一些聚合函数
- package com.jiepu.testdbutil;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.Date;
- import java.util.List;
- import java.util.Map;
- import org.apache.commons.dbutils.QueryRunner;
- import org.apache.commons.dbutils.ResultSetHandler;
- import org.apache.commons.dbutils.handlers.BeanHandler;
- import org.apache.commons.dbutils.handlers.BeanListHandler;
- import org.apache.commons.dbutils.handlers.MapHandler;
- import org.apache.commons.dbutils.handlers.MapListHandler;
- import org.apache.commons.dbutils.handlers.ScalarHandler;
- import org.junit.AfterClass;
- import org.junit.BeforeClass;
- import org.junit.Test;
- import org.sqlite.SQLiteDataSource;
- //http://www.cnblogs.com/liuwt365/p/4111584.html
- public class TestDBUtils {
- private static SQLiteDataSource dataSource;
- private static QueryRunner runner;
- private static String tableName="User";
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- dataSource= new SQLiteDataSource();
- dataSource.setUrl("jdbc:sqlite:testdbutil.db");
- runner=new QueryRunner(dataSource);
- execute("CREATE TABLE IF NOT EXISTS "+tableName+"(id integer primary key autoincrement, name varchar(50),password varchar(50)," +
- "age integer,createdate integer)",dataSource);
- }
- public static int execute(String sql ,SQLiteDataSource dataSource){
- Statement statement;
- int result =0;
- try {
- statement = dataSource.getConnection().createStatement();
- result= statement.executeUpdate(sql);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return result;
- }
- @Test
- public void Query1() throws Exception
- {
- //String sql="INSERT INTO users VALUES ('U002','tom','4321' )";
- //runner.update(sql);
- String sql="INSERT INTO "+tableName+"(name,password,age,createdate) VALUES (?,?,?,?)";
- runner.update(sql,"Jim","123456","24",new Date().getTime());
- runner.update(sql,"Kim","1234567","24",new Date().getTime());
- runner.update(sql,"北京","12345678","24",new Date().getTime());
- runner.update(sql,"嘉兴","123456789","24",new Date().getTime());
- runner.update(sql,"tom","123456789","24",new Date().getTime());
- System.out.println(dataSource);
- }
- @Test
- public void Query2() throws Exception
- {
- //String sql=" UPDATE users SET NAME='Kim' WHERE NAME='jim' ";
- //runner.update(sql);
- String sql=" UPDATE "+tableName+" SET name=? WHERE name=? ";
- runner.update(sql,"lily","Kim");
- Query5();
- }
- @Test
- public void Query3() throws Exception
- {
- //String sql="DELETE FROM users WHERE NAME='lily' ";
- //runner.update(sql);
- String sql="DELETE FROM "+tableName+" WHERE name=? ";
- runner.update(sql,"tom");
- Query5();
- }
- @Test
- public void Query4() throws Exception
- {
- //String sql="SELECT * FROM users where id ='U002' ";
- //user u= runner.query(sql, new BeanHandler<user>(user.class));
- String sql="SELECT * FROM "+tableName+" where id =? ";
- User u=runner.query(sql, new BeanHandler<User>(User.class),"2");
- System.out.println(u);
- }
- @Test
- public void Query5() throws Exception
- {
- String sql="select * from "+tableName;
- List<User> list= runner.query(sql, new BeanListHandler<User>(User.class));
- for(User u:list)
- {
- System.out.println(u);
- }
- }
- @Test
- public void Query6() throws Exception
- {
- String sql="select id,name,password from "+tableName;
- Map<String, Object> map= runner.query(sql, new MapHandler());
- System.out.println(map.toString());
- }
- @Test
- public void Query7() throws Exception
- {
- String sql="select id,name,password from "+tableName;
- List<Map<String , Object>> list= runner.query(sql, new MapListHandler());
- System.out.println(list);
- }
- @Test
- public void Query8() throws Exception
- {
- String sql="select count(*) from "+tableName;
- Object obj=runner.query(sql, new ScalarHandler());
- int i=Integer.valueOf(obj.toString());
- System.out.println(i);
- }
- @Test
- public void batch()
- {
- /**String sql="INSERT INTO "+tableName+"(name,password,age,createdate) VALUES (?,?,?,?)";
- List<User> users=new ArrayList<User>();
- users.add(new User());
- runner.batch(sql, users.toArray());
- Query5();*/
- }
- @Test
- public void custom() throws SQLException
- {
- ResultSetHandler<User[]> h = new ResultSetHandler<User[]>() {
- public User[] handle(ResultSet rs) throws SQLException {
- if (!rs.next()) {
- return null;
- }
- ResultSetMetaData meta = rs.getMetaData();
- int cols = meta.getColumnCount();
- User[] result = new User[cols];
- for (int i = 0; i < cols; i++) {
- User user=new User();
- user.setId(rs.getInt(1));
- user.setName(rs.getString(2));
- user.setPassword(rs.getString(3));
- user.setAge(rs.getLong(4));
- user.setCreatedate(rs.getLong(5));
- result[i]=user;
- rs.next();
- }
- return result;
- }
- };
- User[] result = runner.query("SELECT * FROM "+tableName+" WHERE age=?", h, "24");
- for (User user : result) {
- System.out.println(user);
- }
- }
- //http://wenku.baidu.com/view/6d4bb27602768e9951e73849.html
- @AfterClass
- public static void setUpAfterclass()
- {
- dataSource=null;
- runner=null;
- }
- }
- package com.jiepu.testdbutil;
- public class User {
- //使用dbutil 实体类成员不要使用基本类型int long 应该使用封装类型 Integer Long
- private Integer id;
- private String name;
- private String password;
- private Long age;
- private Long createdate;
- public Integer getId() {
- return id;
- }
- public void setId(Integer 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;
- }
- public Long getAge() {
- return age;
- }
- public void setAge(Long age) {
- this.age = age;
- }
- public Long getCreatedate() {
- return createdate;
- }
- public void setCreatedate(Long createdate) {
- this.createdate = createdate;
- }
- @Override
- public String toString() {
- return "User [id=" + id + ", name=" + name + ", password=" + password
- + ", age=" + age + ", createdate=" + createdate + "]";
- }
- }
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.jiepu</groupId>
- <artifactId>testdbutil</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>testdbutil</name>
- <url>http://maven.apache.org</url>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.8.1</version>
- </dependency>
- <dependency>
- <groupId>commons-dbutils</groupId>
- <artifactId>commons-dbutils</artifactId>
- <version>1.6</version>
- </dependency>
- <dependency>
- <groupId>org.xerial</groupId>
- <artifactId>sqlite-jdbc</artifactId>
- <version>3.8.7</version>
- </dependency>
- </dependencies>
- </project>