List<User> list = queryRunner.query("select * from user_info limit 100", new ResultSetHandler<List<User>>() {@Overridepublic List<User> handle(ResultSet rs)throws SQLException { List<User> l = new ArrayList<User>();while (rs.next()) { User user = new User(); user.setUserId(rs.getInt("user_id")); user.setUserName(rs.getString("user_name")); user.setCreateTime(rs.getTimestamp("create_time")); l.add(user); }return l; }});
List<User> list = queryRunner.query("select * from user_info limit 100", rs -> { List<User> l = new ArrayList<User>();while (rs.next()) { User user = new User(); user.setUserId(rs.getInt("user_id")); user.setUserName(rs.getString("user_name")); user.setCreateTime(rs.getTimestamp("create_time")); l.add(user); }return l;});
long count = queryRunner.query("select count(*) from user_info", new ScalarHandler<Long>()); // 查询countString userName = queryRunner.query("select user_name from user_info where user_id=?", new ScalarHandler<String>(), 1); // 查询user_id=1的用户的用户名
ColumnListHandler
返回查询结果(所有行)第一列的数据List:
1
List<String> userNameList = queryRunner.query("select user_name from user_info", new ColumnListHandler<String>()); // 查询所有用户的user_name
MapHandler
返回查询结果第一行数据(所有列)并组装成Map,Map的key为列名,value为值:
123
Map<String, Object> userInfo = queryRunner.query("select user_id,user_name from user_info where user_id=1", new MapHandler());long userId = (Long) userInfo.get("user_id");String userName = (String) userInfo.get("user_name");
List<Map<String, Object>> dataList = queryRunner.query("select user_id,user_name from user_info", new MapListHandler());
ArrayHandler
返回查询结果第一行数据,将所有列值按顺序组成一个数据:
123
Object[] data = queryRunner.query("select user_id,user_name from user_info where user_id=1", new ArrayHandler());long userId = (Long) data[0];String userName = (String) data[1];
publicclassUser{privateint userId;private String userName;privateint userAge;private Date createTime;// 省略getter setter}
执行查询:
12
// 查询user_id=1的用户数据并返回User对象User user = queryRunner.query("select user_id as userId,user_name as userName,user_age as userAge,create_time as createTime from user_info where user_id=1", new BeanHandler<User>(User.class));
User user = queryRunner.query("select user_id,user_name,user_age,create_time from user_info where user_id=1",new BeanHandler<User>(User.class, new BasicRowProcessor(new GenerousBeanProcessor())));
List<User> userList = queryRunner.query("select user_id as userId,user_name as userName,user_age as userAge,create_time as createTime from user_info",new BeanListHandler<User>(User.class));
同样也可以将带有下划线分隔符的列名映射到驼峰命名的Java对象上:
12
List<User> userList = queryRunner.query("select user_id,user_name,user_age,create_time from user_info",new BeanListHandler<User>(User.class, new BasicRowProcessor(new GenerousBeanProcessor())));