Apache-DBUtils
开源的JDBC工具类,对JDBC的简单封装
SQL操作交给了QueryRunner的实例
Maven依赖
commons-dbutils
commons-dbutils
1.7
插入语句测试【删改同理操作】
@Testpublic void dbTest() throwsSQLException {
QueryRunner queryRunner= newQueryRunner();
Connection connectionByOriginalJdbc=CompleteJdbcUtils.getConnectionByOriginalJdbc();
String sql= "insert into user(user_name,user_password,user_createTime) values(?,?,?);";int update = queryRunner.update(connectionByOriginalJdbc, sql, "你弟含王", "121314",CompleteJdbcUtils.parseToSqlDate("1997-09-06"));
System.out.println(update);
CompleteJdbcUtils.releaseResource(connectionByOriginalJdbc,null,null);
}
查询单个的QueryRunner
- BeanHandler
@Testpublic void dbTest2() throwsSQLException {
QueryRunner queryRunner= newQueryRunner();
Connection connectionByOriginalJdbc=CompleteJdbcUtils.getConnectionByHikari();//实体类处理器对象
BeanHandler beanHandler = new BeanHandler(User.class);
String sql= "select * from user where user_id = ?;";//根据BeanHandler反射过去 只能处理单个对象返回
User query = queryRunner.query(connectionByOriginalJdbc, sql, beanHandler,3);
System.out.println(query);
CompleteJdbcUtils.releaseResource(connectionByOriginalJdbc,null,null);
}
用Map封装单个记录的 MapHandler,默认泛型
@Testpublic void dbTest21() throwsSQLException {
QueryRunner queryRunner= newQueryRunner();
Connection connectionByOriginalJdbc=CompleteJdbcUtils.getConnectionByHikari();//实体类处理器对象
MapHandler mapHandler = new MapHandler(); //
String sql = "select * from user where user_id = ?;";//根据BeanHandler反射过去 只能处理单个对象返回
Map map = queryRunner.query(connectionByOriginalJdbc, sql, mapHandler, 3);
System.out.println(map);
CompleteJdbcUtils.releaseResource(connectionByOriginalJdbc,null,null);
}
多个记录的BeanListHandler处理
@Testpublic void dbTest3() throwsSQLException {
QueryRunner queryRunner= newQueryRunner();
Connection connectionByOriginalJdbc=CompleteJdbcUtils.getConnectionByHikari();//实体类处理器对象
BeanListHandler beanHandler = new BeanListHandler(User.class);
String sql= "select * from user;";//根据BeanHandler反射过去 返回List集合封装的对象的处理
List users =queryRunner.query(connectionByOriginalJdbc, sql, beanHandler);for(User user:users) {
System.out.println(user);
}
CompleteJdbcUtils.releaseResource(connectionByOriginalJdbc,null,null);
}
或者是MapListHandler,泛型是
@Testpublic void dbTest31() throwsSQLException {
QueryRunner queryRunner= newQueryRunner();
Connection connectionByOriginalJdbc=CompleteJdbcUtils.getConnectionByHikari();//实体类处理器对象
MapListHandler mapListHandler = newMapListHandler();
String sql= "select * from user;";
List> maps =queryRunner.query(connectionByOriginalJdbc, sql, mapListHandler);for(Map map:maps) {
System.out.println(map);
}
CompleteJdbcUtils.releaseResource(connectionByOriginalJdbc,null,null);
}
ScalarHandler 用于特殊值的获取,例如聚合函数的操作
https://www.bilibili.com/video/BV1eJ411c7rf?p=53
自定义结果集处理器的方法
https://www.bilibili.com/video/BV1eJ411c7rf?p=54