结果集常用类实现

List为空的类返回值是[]、没有List的类为空返回值是null

  1. sql = "select * from category";
  2. // ArrayHandle
  3. // 只获取首行数据
  4. Arrays.toString(queryRunner.query(sql, new ArrayHandler()));
  5. // ArrayListHander
  6. // 获取多行数据
  7. List<Object[]> query = queryRunner.query(sql, new ArrayListHandler());
  8. for(Object[] objs: query){
  9. System.out.println("category_id:" + objs[0]);
  10. System.out.println("category_name:" + objs[1]);
  11. }
  12. // BeanHandler
  13. // 获取一个对象
  14. Category query = queryRunner.query(sql, new BeanHandler<>(Category.class));
  15. System.out.println(query.getCategory_id());
  16. System.out.println(query.getCategory_name());
  17. // BeanListHandler
  18. // 获取对象数组
  19. List<Category> query = queryRunner.query(sql, new BeanListHandler<>(Category.class));
  20. for(Category cat: query){
  21. System.out.println(cat.getCategory_id() +"——"+ cat.getCategory_name());
  22. }
  23. // MapHandler
  24. // 获取一个map字典
  25. Map<String, Object> query = queryRunner.query(sql, new MapHandler());
  26. System.out.println(query.getOrDefault("category_id", "0"));
  27. System.out.println(query.getOrDefault("category_name", "null"));
  28. // MapListHandler
  29. List<Map<String, Object>> query = queryRunner.query(sql, new MapListHandler());
  30. for(Map map: query){
  31. System.out.println(map.getOrDefault("category_id", "0") +"——"+
  32. map.getOrDefault("category_name", "null"));
  33. }

数据库操作函数

  1. queryRunner.update(sql);
  2. int update("insert into table value(...)"); // 增
  3. int update("delete from table where id=1"); // 删
  4. int update("update table set id=2 where id=1");//改
  5. queryRunner.query(sql, rsh);
  6. ResultSetHandler query("select * from table", new ResultSetHandler());

基本用法

初始化线程池

  1. public class PoolUtils {
  2. private static DataSource dataSource = null;
  3. static {
  4. //完成连接池的初始化
  5. InputStream ips = PoolUtils.class.getClassLoader().getResourceAsStream("druid.properties");
  6. Properties properties = new Properties();
  7. try {
  8. properties.load(ips);
  9. } catch (IOException e) {
  10. e.printStackTrace();
  11. }
  12. try {
  13. dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. /**
  19. * 对外提供连接!
  20. */
  21. public static DataSource getDataSource() {
  22. return dataSource;
  23. }
  24. /**
  25. * 对外提供获取连接的方法!
  26. */
  27. public static Connection getConnection() throws SQLException {
  28. //使用连接池获取连接返回
  29. return dataSource.getConnection();
  30. }
  31. }
  1. public class test{
  2. private static QueryRunner queryRunner = new QueryRunner(PoolUtils.getDataSource());
  3. private static String sql = "select * from category";
  4. public static void main(String[] args) throw SQLException {
  5. System.out.println(Arrays.toString(queryRunner.query(sql, new ArrayHandler())));
  6. }
  7. }