1. org.apache.commons.dbutils (该包中的类主要帮助我们更便捷的操作JDBC)
2. org.apache.commons.dbutils.handlers(该包中的类都是实现org.apache.commons.dbutils.ResultSetHandler接口的实现类)
3. org.apache.commons.dbutils.wrappers(该包中的类主要是封装了对Sql结果集的操作)
使用这个DbUtils的一些优势:
1. 防止了资源的泄露,写一段JDBC的准备代码其实并不麻烦,但是那些操作确实是十分耗时和繁琐的,也会导致有时候数据库连接忘记关闭了导致异常难以追踪。
2. 干净整洁的持久化代码,把数据持久化到数据库的代码被打打削减,剩下的代码能够清晰简洁的表达你的操作目的。
3. 自动把ResultSets中的工具映射到JavaBean中,你不需要手动的使用Setter方法将列值一个个赋予相应的时日,Resultset中的每一个行都大表一个完成的Bean实体。
要学习如何使用这个框架,最简单的方式就是用它写个Demo-CRUD操作,让我们先做个准备动作在Mysql中建立一个测试专用表Visitor。
/*创建Visitor*/
CREATE TABLE Visitor
(
Id INT(11) NOT NULL AUTO_INCREMENT,
Name VARCHAR(1000) NOT NULL,
Email VARCHAR(1000) NOT NULL,
Status INT NOT NULL DEFAULT 1,
CreateTime DateTime,
PRIMARY KEY(Id)
)
建完表结构,我们就可以学习怎么利用框架中的Utils类帮助我们完成CRUD-DEMO,其实对于这个框架主要操作的是ResultSetHandler接口的实现类与QueryRunner类
创建对应的JavaBean实体类如下:
package david.apache.model;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Visitor {
private int id;
private String name;
private String email;
private int status;
private Date createTime;
public Visitor() {
// TODO Auto-generated constructor stub
setCreateTime(new Date());
}
public Visitor(String name, String email) {
this.setName(name);
this.setEmail(email);
this.setStatus(1);
this.setCreateTime(new Date());
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return String.format("{Id: %d, Name: %s, Email: %s, CreateTime: %s}", getId(), getName(), getEmail(),
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(getCreateTime()));
}
}
private static Connection getConnection() {
Connection conn = null;
try {
Class.forName(CONNECTION_DRIVER_STR);
conn = DriverManager.getConnection(CONNECTION_STR, "root", "123456");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/*
* 新增Visitor, ScalarHandler的demo
*/
public static void insertVisitor(Visitor visitor) {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
String sql = "insert into visitor (Name, Email, Status, CreateTime) values (?, ?, ?, ?)";
try {
int count = qr.update(conn, sql, visitor.getName(), visitor.getEmail(), 1, new Date());
BigInteger newId = (BigInteger) qr.query(conn, "select last_insert_id()", new ScalarHandler(1));
visitor.setId(Integer.valueOf(String.valueOf(newId)));
System.out.println("新增" + count + "条数据=>Id:" + newId);
} catch (SQLException e) {
e.printStackTrace();
}
}
大家可以看到操作的步骤其实很简单,也是写SQL可以了,对于自增字段我们通过select last_insert_id()的方法利用ScalarHandler
删除方法
public static void deleteVisitor(int id) {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
String sql = "delete from visitor where status>0 and id=?";
try {
int count = qr.update(conn, sql, id);
System.out.println("删除" + count + "条数据。");
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static Visitor retrieveVisitor(int id) {
Connection conn = getConnection();
Visitor visitor = null;
QueryRunner qr = new QueryRunner();
String sql = "select * from visitor where status>0 and id=?";
try {
visitor = (Visitor) qr.query(conn, sql, new BeanHandler(Visitor.class), id);
System.out.println(visitor);
return visitor;
} catch (Exception e) {
e.printStackTrace();
}
return visitor;
}
public static void updateVisitor(int id) {
Visitor visitor = retrieveVisitor(id);
System.out.println("更新前:" + visitor);
Connection conn = getConnection();
String updateFieldStr = visitor.getName();
QueryRunner qr = new QueryRunner();
String sql = "update visitor set Name = ?, Email = ?, Status = ?, CreateTime = ? where status>0 and Id = ?";
if (updateFieldStr.contains("updated")) {
updateFieldStr = updateFieldStr.substring(0, updateFieldStr.indexOf("updated"));
} else {
updateFieldStr = updateFieldStr + "updated";
}
visitor.setName(updateFieldStr);
try {
int count = qr.update(conn, sql, new Object[] { visitor.getName(), visitor.getName(), visitor.getStatus(),
visitor.getCreateTime(), visitor.getId() });
System.out.println("更新了" + count + "条数据");
System.out.println("更新后:" + visitor);
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void getVisitorList() {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
String sql = "select * from visitor where status>0";
try {
List ls = qr.query(conn, sql, new BeanListHandler(Visitor.class));
for (Visitor visitor : ls) {
System.out.println(visitor);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void getVisitWithMap(int id) {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
String sql = "select * from visitor where status>0 and id=?";
try {
Map map = qr.query(conn, sql, new MapHandler(), id);
Integer visitorId = Integer.valueOf(map.get("Id").toString());
String visitorName = map.get("Name").toString();
String visitorEmail = map.get("Email").toString();
Integer visitorStatus = Integer.valueOf(map.get("Status").toString());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date visitorCreateTime = sdf.parse(map.get("CreateTime").toString());
Visitor visitor = new Visitor(visitorName, visitorEmail);
visitor.setId(visitorId);
visitor.setStatus(visitorStatus);
visitor.setCreateTime(visitorCreateTime);
System.out.println(visitor);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void getVisitWithMapLs() {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
String sql = "select * from visitor where status>0";
try {
List
本文转自【http://www.blogjava.net/davidjefiny/archive/2014/01/05/apache_common_dbutils.html】
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则作者保留追究法律责任的权利