Apache DBUtils
下载Commons-dbutils-1.7.jar,其中包含一下几个重点类:
Dbutils、QueryRunner、ResultSetHandler
1.DuUtils:辅助
2.QueryRunner:增删改查
update()
query()
oracle:dml,commit
mysql:dml自动提交
3.如果是查询,则需要ResultSetHandler接口,有很多实现类,一个实现类对应于一种不同的查询类型
实现类ArrayHandler:返回结果集的第一行数据,并用Object[]接收
实现类ArrayListHandler:返回结果的多行数据,List<Object[]>
实现类BeanHandler:返回结果集的第一行数据,用对象()接受
实现类BeanListHandler:返回结果集的多行数据,用对象()接受
实现类BeanMapHandler:返回结果集的多行数据,用对象()接受
//反射会通过无参构造来创建对象
/查询单行数据
public static void testArrayHandler() throws SQLException {
QueryRunner runner=new QueryRunner(DataSourceUtil.getDataSourceWithC3P0ByXml());//自动提交事务
Object[] student = runner.query("select * from student where sno>?", new ArrayHandler(), 1);
System.out.println(student[0]+","+student[1]+","+student[2]+","+student[3]);
}
//查询多行数据
public static void testArrayListHandler() throws SQLException {
QueryRunner runner=new QueryRunner(DataSourceUtil.getDataSourceWithC3P0ByXml());//自动提交事务
List<Object[]> students = runner.query("select * from student where sno>?", new ArrayListHandler(), 1);
for(Object[] student:students){
System.out.println(student[0]+","+student[1]+","+student[2]+","+student[3]);
}
}
//查询单行数据(放入对象中)
public static void testBeanHandler() throws SQLException {
QueryRunner runner=new QueryRunner(DataSourceUtil.getDataSourceWithC3P0ByXml());//自动提交事务
Student student = runner.query("select * from student where sno>?", new BeanHandler<Student>(Student.class), 1);
System.out.println(student.getSno()+","+student.getSname()+","+student.getSage()+","+student.getSaddress());
}
//查询多行数据(放入对象中)
public static void testBeanListHandler() throws SQLException {
QueryRunner runner=new QueryRunner(DataSourceUtil.getDataSourceWithC3P0ByXml());//自动提交事务
List<Student> students= runner.query("select * from student where sno>?", new BeanListHandler<Student>(Student.class), 1);
for(Student student:students){
System.out.println(student.getSno()+","+student.getSname()+","+student.getSage()+","+student.getSaddress());
}
}
//查询多行数据(map) ---jav中oracle默认的数值类型 BigDecimal
public static void testBeanMapHandler() throws SQLException {
QueryRunner runner=new QueryRunner(DataSourceUtil.getDataSourceWithC3P0ByXml());//自动提交事务
Map<BigDecimal, Student> students = runner.query("select * from student where sno>?", new BeanMapHandler<BigDecimal,Student>(Student.class,"sno"), 1);
for(Map.Entry<BigDecimal, Student> student:students.entrySet()){
System.out.println(student.getKey()+":"+student.getValue());
}
Student student=students.get(new BigDecimal(3));//int
System.out.println(student.getSno()+","+student.getSname()+","+student.getSage()+","+student.getSaddress());
原文:https://www.cnblogs.com/mayouyou/p/13159352.html