DBUtils是JDBC的简化开发工具包,需要使用连接池,SQL语句。开发中常用的查询方法使用 BeanListHandler、BeanHandler、ScalarHandler的情况较多,需要牢牢掌握。
public void queryById() {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql = "select * from user where uid=?";
Object[] params = { };
try {
User user = queryRunner.query(sql, new BeanHandler<>(User.class), params);
System.out.println(user);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void queryAll() {
try {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql = "select * from user";
List<User> users = queryRunner.query(sql, new BeanListHandler<User>(User.class));
users.stream().forEach(user -> System.out.println(user));
List<Map<String, Object>> list = queryRunner.query(sql, new MapListHandler());
list.stream().forEach(map->System.out.println(map));
List<Object> query = queryRunner.query(sql, new ColumnListHandler("uname"));
query.stream().forEach(obj->System.out.println(obj));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void testCount() {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql = "select count(*) from user";
try {
long count = (long) queryRunner.query(sql, new ScalarHandler());
System.out.println(count);
} catch (SQLException e) {
e.printStackTrace();
}
}