一、关于DbUtils
commons-dbutils 是 Apache 组织提供的一个开源 JDBC 工具类库,对传统操作数据库的类进行二次封装,可以把结果集转化成List。
项目主页:
http://commons.apache.org/dbutils/
文档地址:
http://commons.apache.org/dbutils/examples.html
下载地址:
http://commons.apache.org/downloads/download_dbutils.cgi
(1)org.apache.commons.dbutils
DbUtils : 提供如关闭连接、装载 JDBC 驱动程序等常规工作的工具类
QueryRunner : 该类简单化了 SQL 查询,它与 ResultSetHandler 组合在一起使用可以完成大部分的数据库操作,能够大大减少编码量。
QueryLoader : 属性文件加载器,主要用于加载属性文件中的 SQL 到内存中。
(2)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
(3)org.apache.commons.dbutils.wrappers
SqlNullCheckedResultSet :该类是用来对sql语句执行完成之后的的数值进行null的替换。
StringTrimmedResultSet :去除ResultSet中中字段的左右空格。Trim()
二、例子
public class TestDbUtils {
/**
* BeanListHandler :将ResultSet中所有的数据转化成List,List中存放的是类对象
*/
public static void getBeanListData() {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
try {
ResultSetHandler rsh = new BeanHandler(TUser.class);
TUser usr = (TUser) qr.query(conn,"SELECT id,username,gender FROM t_user WHERE id=10000",rsh);
System.out.println(StringUtils.center("findById", 50, '*'));
System.out.println("id=" + usr.getId() + " name=" + usr.getUsername() + " gender=" + usr.getGender());
List results = (List) qr.query(conn,"SELECT id,username,gender FROM t_user",
new BeanListHandler(TUser.class));
System.out.println(StringUtils.center("findAll", 50, '*'));
for (int i = 0; i < results.size(); i++) {
TUser user = (TUser) results.get(i);
System.out.println("id=" + user.getId() + " name=" + user.getUsername() + " gender=" + user.getGender());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
/**
* MapListHandler :将ResultSet中所有的数据存成List。List中存放的是Map
*/
public static void getMapListData() {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
try {
List results = (List) qr.query(conn,"SELECT id,username,gender FROM t_user",
new MapListHandler());
for (int i = 0; i < results.size(); i++) {
Map map = (Map) results.get(i);
System.out.println("id=" + map.get("id") + " name=" + map.get("username") + " gender=" + map.get("gender"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
/**
*新增和更新例子
*/
public static void insertAndUpdateData(){
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
try{
//创建一个数组来存要insert的数据
Object[] insertParams = {"John Doe", "000000","男"};
int inserts = qr.update(conn, "INSERT INTO t_user(username,password,gender) VALUES (?,?,?)",
insertParams );
System.out.println("inserted " + inserts + " data");
Object[] updateParams = {"111111", "John Doe"};
int updates = qr.update(conn, "UPDATE t_user SET password=? WHERE username=?",
updateParams );
System.out.println("updated "+ updates + " data");
}catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
/**
* Unlike some other classes in DbUtils, this class(SqlNullCheckedResultSet) is NOT thread-safe.
*/
public static void findUseSqlNullCheckedResultSet(){
Connection conn = getConnection();
try{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, username, gender FROM t_user");
SqlNullCheckedResultSet wrapper = new SqlNullCheckedResultSet(rs);
wrapper.setNullString("N/A"); // Set null string
rs = ProxyFactory.instance().createResultSet(wrapper);
while(rs.next()){
System.out.println("id="+rs.getInt("id") + " username=" + rs.getString("username")
+ " gender="+rs.getString("gender"));
}
rs.close();
}catch(Exception e){
e.printStackTrace();
}finally{
DbUtils.closeQuietly(conn);
}
}
/****数据库连接*** */
public static Connection getConnection() {
Connection conn = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1/springapp?useUnicode=true&characterEncoding=gb2312";
DbUtils.loadDriver(driver);
try {
conn = DriverManager.getConnection(url, "root", "root");
} catch (SQLException ex) {
ex.printStackTrace();
}
return conn;
}
}