您的位置:首页 > 其它

用dbUtils工具类(原生jdbc)来进行查询和批处理

2016-03-12 00:43 1486 查看
导入commons-dbutils-xxx.jar包。

主要用的就一个类和一个接口及其5个实现类。

类:QueryRunner

接口:ResultSetHandler ,实现类BeanHandler , BeanListHandler , MapHandler , MapListHandler , ScalarHandler ,最常用的还是前两个实现类。

1.(批处理)增删改都可以用同一个方法实现:queryRunner.update(Connection conn, String sql, Object... params)方法,传入Connection对象、sql语句,如果有参数列表的,再传入参数列表:

@Test
public void testQueryRunner() throws Exception {
DataSource dataSource = new ComboPooledDataSource();
Connection conn = dataSource.getConnection();
QueryRunner qr = new QueryRunner();
String sql1 = "insert into  employee (name,age,city) values ('x',13,'beijing'),('xx',14,'shanghai'),('xxx',15,'guangzhou')";
qr.update(conn, sql1);
String sql2 = "update employee set age=? where id>=?";
qr.update(conn, sql2, 20, 2);// 把id大于等于2的记录的age变成20
String sql3 = "delete from employee where id>?";
qr.update(conn, sql3, 1);
}


2.查询。以上批量增删改的时候没有用到ResultSetHandler接口,查询的时候就要用到了。

BeanHandler用于返回一个实体类对象。

BeanListHandler用于返回一个list,元素类型即操作的实体类类型。

MapHandler用于返回一个Map对象,此Map对象的键即为实体类的属性名,值即为实体类的属性值。

MapListHandler用于返回一个包含多个Map对象的list。

ScalarHandler有两个作用,既可以返回总记录数,又可以返回单条记录的某个字段值,也就是单个对象的某个属性值。

其实,从名字上就可以看出每个实现类返回的类型,从而根据需求挑选合适的实现类。

以BeanHandler实现类为例:

@Test
public void testBeanHandler() throws SQLException {
DataSource dataSource = new ComboPooledDataSource();
Connection conn = dataSource.getConnection();
QueryRunner qr = new QueryRunner();
String sql = "select * from employee where id=?";
ResultSetHandler<Employee> rsh = new BeanHandler<Employee>(Employee.class);
Employee employee = qr.query(conn, sql, rsh, 3);
System.out.println(employee);
}


其他的实现类自己在学习的时候都测试过了,很简单,这里就不叙述了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: