Common Dbutils是操作数据库的组件,对传统操作数据库的类进行二次封装,可以把结果集转化成List。
主要方法:
DbUtils类:启动类
ResultSetHandler接口:转换类型接口
MapListHandler类:实现类,把记录转化成List
BeanListHandler类:实现类,把记录转化成List,使记录为JavaBean类型的对象
Qrery Runner类:执行SQL语句的类
建立三个Java文件
命名为BeanListExample.java
Guestbook.java
MapListExample.java
源码:
BeanListExample.java
package com.sy;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
public class BeanListExample {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/people";
String jdbcDriver = "com.mysql.jdbc.Driver";
String user = "root";
String password = "hicc";
DbUtils.loadDriver(jdbcDriver);
try {
conn = DriverManager.getConnection(url, user, password);
QueryRunner qr = new QueryRunner();
List results = (List) qr.query(conn, "select id,name from guestbook", new BeanListHandler(Guestbook.class));
for (int i = 0; i < results.size(); i++) {
Guestbook gb = (Guestbook) results.get(i);
System.out.println("id:" + gb.getId() + ",name:" + gb.getName());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
}
Guestbook.java
Code
MapListExample.java
Code
使用组建好需要添加commons-dbutils-1.1.jar和mysql-connector-java-5.1.6-bin.jar两个jar包。
配置完毕!!!
来源:oschina
链接:https://my.oschina.net/u/265431/blog/70758