QueryRunner类结果集处理的八种方法
在连接数据库的时候(MySQL)时,会遇到的问题。
调用QueryRunner的方法是:
query(Connection con,String Sql,ResultSetHandler r,Object.params)
MapListHandler
将结果集每一行存储到Map集合中,键:列名;值:数据
public static void mapListHandler()throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "select * from db";
Lsit<Map<String,Object>> list = qr.query(con,sql,new MapListHandler());
for(Map<String,Object> map:list){
System.out.print(key+'..'+map.get(key));
}
System.out.prinln();
}
MapHandler
将结果集的第一行数据,封存到Map集合中
public static void mapHandler()throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "select * from db";
Map map = qr.query(con,sql,new MapHandler());
for(String key:map.keySet()){
System.out.print(key+'..'+map.get(key));
}
System.out.prinln();
}
ScalarHandler
查询后,只有一个结果
Public static void scalarHandler() throws SQLException(){
QueryRunner qr = new QueryRunner();
String sql = "select * from db";
long count = qr.query(con,sql,new ScalarHandler());
System.out.prinln(count);
}
ColumnListHandler
结果集,指定列的数据存储到List集合中,
List每个列数据类型不同。
public static void columnListHandler()throws SQLException(){
QueryRunner qr = new QueryRunner();
String sql = "select * from db";
List<Object> list = qr.query(con,sql,new ColumnListHandler<Object>("name"));
for(Object obj:list){
System.out.println(obj);
}
System.out.prinln(obj);
}
BeanListHandler
结果集每一行数据,封装JavaBean对象
多个JavaBean对象,存储到List集合
public static void columnListHandler()throws SQLException(){
QueryRunner qr = new QueryRunner();
String sql = "select * from db";
List list = qr.query(con,sql,new BeanListHandler<Sort>(Sort.class));
for(Sort s:list){
System.out.println(s);
}
}
BeanHandler
将结果集的第一行数据,封装成JavaBean对象
public static void beanHandler()throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort ";
Sort s = qr.query(con, sql, new BeanHandler<Sort>(Sort.class));
System.out.println(s);
}
ArrayListHandler
将结果集的每一行,封装到对象数组中
public static void arrayListHandler()throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort";
List<Object[]> result= qr.query(con, sql, new ArrayListHandler());
for( Object[] objs : result){
for(Object obj : objs){
System.out.print(obj+" ");
}
System.out.println();
}
}
ArrayHandler
将结果集的第一行存储到对象数组中 Object[]
public static void arrayHandler()throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort";
Object[] result = qr.query(con, sql, new ArrayHandler());
for(Object obj : result){
System.out.print(obj);
}
}
}
本文来自博客园,作者:Felix_CAI,转载请注明原文链接:https://www.cnblogs.com/Believe-oneself/p/13768476.html