// 1)BeanHandler: 查询返回单个对象
@Test
public void testQueryOne() throws Exception {
String sql = "select * from admin where id=?";
// 获取连接
conn = JdbcUtil.getConnection();
// 创建DbUtils核心工具类对象
QueryRunner qr = new QueryRunner();
// 查询返回单个对象
Admin admin = qr.query(conn, sql, new BeanHandler<Admin>(Admin.class), 29);
System.out.println(admin);
conn.close();
}
// 2)BeanListHandler: 查询返回list集合,集合元素是指定的对象
@Test
public void testQueryMany() throws Exception {
String sql = "select * from admin where id<? and pwd!=?";
conn = JdbcUtil.getConnection();
QueryRunner qr = new QueryRunner();
// 查询全部数据
//List<Admin> list = qr.query(conn, sql, new BeanListHandler<Admin>(Admin.class));
List<Admin> list = qr.query(conn, sql,new Object[]{29,"555"}, new BeanListHandler<Admin>(Admin.class));
System.out.println("集合含有"+list.size()+"个元素:"+list);
conn.close();
}
自定义封装结果集数据:
public void testQuery() throws Exception {
String sql = "select * from admin where id<?";
// 获取连接
conn = JdbcUtil.getConnection();
// 创建DbUtils核心工具类对象
QueryRunner qr = new QueryRunner();
// 查询
List<Admin> list = new ArrayList<Admin>();
list = (List<Admin>) qr.query(conn, sql, new ResultSetHandler<List<Admin>>() {
// 如何封装一个Admin对象
public List<Admin> handle(ResultSet rs) throws SQLException {
List<Admin> adminList = new ArrayList<Admin>();
while (rs.next()) {
Admin admin = new Admin();
admin.setId(rs.getInt("id"));
admin.setUserName(rs.getString("userName"));
admin.setPwd(rs.getString("pwd"));
adminList.add(admin);
}
return adminList;
}
}, 29);
// 测试
System.out.println(list);
// 关闭
conn.close();
}
引入commons-dbutils-1.6.jar,commons-logging-1.1.3.jar.