commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,
并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。
•API介绍:
–org.apache.commons.dbutils.QueryRunner
–org.apache.commons.dbutils.ResultSetHandler
以下介绍ResultSetHandler的几个常用的Handler(结果处理理类)
1.BeanHandler(注意当查询的字段在数据库中时多个单词组成的字段时,必须通过指定别名来实现数据库字段和Javabean
属性之间的映射,否则最终Javabean的属性值为null)
/**
* BeanHandler:把结果集的第一条记录转为创建BeanHandler对象时传入的class参数对应的对象。
* @throws Exception
*/
@Test
public void testBeanHanlder() throws Exception {
Connection connection = null;
try {
connection = JDBCTools.getConnection();
String sql = "select id,name,email,brith,core from Customerss where id = ?";
Customers customers=(Customers) qr.query(connection, sql, new BeanHandler(Customers.class), 2);
System.out.println(customers);
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.colse(null, connection, null);
}
}
@Test
public void testBeanHanlder1() throws Exception {
Connection connection = null;
try {
connection = JDBCTools.getConnection();
String sql = "select KINO_ID kinoId,SEQ_NO seqNo,"
+ "FIELD_ID fieldId,"
+ "FIELD_LABEL fieldLable,"
+ "VISIBLE_KBN visibleKbn,"
+ "NES_KBN nesKbn,"
+ "DEFAULT_VALUE defautValue,"
+ "BIKO biko "
+ "from ACTL_INPUT where KINO_ID ='Afmm1010' and SEQ_NO=?";
ACTL actl = (ACTL) qr.query(connection, sql, new BeanHandler(ACTL.class), 2);
System.out.println(actl);
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.colse(null, connection, null);
}
}
2.BeanListHandler
/**
* BeanListHandler:把结果集转化为一个list,该list不为null,但是可能为空集合(size= 0)
* 若SQL语句的确能够查询到记录,list中存放的创建BeanListHandler传入的class对象对应的对象。
* @throws Exception
*/
@Test
public void testBeanListHanlder() throws Exception {
Connection connection = null;
try {
connection = JDBCTools.getConnection();
String sql = "select id,name,email,brith,core from Customerss ";
List<Customers> list=(List<Customers>) qr.query(connection, sql, new BeanListHandler(Customers.class));
System.out.println(list);
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.colse(null, connection, null);
}
}
3.MapHandler
/**
* MapHandler:返回SQL对应的第一条记录对应的map对象
* @throws Exception
*/
@Test
public void testMapHanlder() throws Exception {
Connection connection = null;
try {
connection = JDBCTools.getConnection();
String sql = "select id,name,email,brith,core from Customerss ";
Map<String,Object> map= qr.query(connection, sql, new MapHandler());
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.colse(null, connection, null);
}
}