用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语句,如果有参数列表的,再传入参数列表:
2.查询。以上批量增删改的时候没有用到ResultSetHandler接口,查询的时候就要用到了。
BeanHandler用于返回一个实体类对象。
BeanListHandler用于返回一个list,元素类型即操作的实体类类型。
MapHandler用于返回一个Map对象,此Map对象的键即为实体类的属性名,值即为实体类的属性值。
MapListHandler用于返回一个包含多个Map对象的list。
ScalarHandler有两个作用,既可以返回总记录数,又可以返回单条记录的某个字段值,也就是单个对象的某个属性值。
其实,从名字上就可以看出每个实现类返回的类型,从而根据需求挑选合适的实现类。
以BeanHandler实现类为例:
其他的实现类自己在学习的时候都测试过了,很简单,这里就不叙述了。
主要用的就一个类和一个接口及其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); }
其他的实现类自己在学习的时候都测试过了,很简单,这里就不叙述了。
相关文章推荐
- 缓存穿透与雪崩
- .net架构设计读书笔记--第二章 第7节 神化般的业务层
- .net架构设计读书笔记--第二章 设计体系结构
- SQL Server 问题 1 - SQL Server encountered error 0x80070422/0x8007042d
- ibatis学习总结
- nyoj-Color the necklace(Ploya定理 + 欧拉函数 + 扩展欧几里得(求逆元))
- PHP学习(七)--分支结构
- <tx:method/> 有关的设置
- 星际争霸 虚空之遗 人族5BB 操作流程
- CI框架如何在主目录application目录之外使用uploadify上传插件和bootstrap前端框架:
- 4.斐波那契数列[尾递归]
- 阿里云 mysql的远程访问问题
- .net架构设计读书笔记--第一章 基础
- QtCreator-----设置编码
- mac gcc 编译错误 基础问题
- 超详细Centos6.5文本模式安装步骤
- POJ 1236 Network of Schools 强连通分量
- C++ exceptional Maximally Reusable Generic Containers
- B. Making a String
- Android开发中实现https校验