:fleur_de_lis: 在连接数据库的时候(MySQL)时,会遇到的问题:QueryRunner类结果处理的八种方法
QueryRunner类结果集处理的八种方法
调用QueryRunner的方法是:
1
| query(Connection con,String Sql,ResultSetHandler r,Object.params)
|
MapListHandler
将结果集每一行存储到Map集合中,键:列名;值:数据
1 2 3 4 5 6 7 8 9
| 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集合中
1 2 3 4 5 6 7 8 9
| 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
查询后,只有一个结果
1 2 3 4 5 6
| 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每个列数据类型不同。
1 2 3 4 5 6 7 8 9
| 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集合
1 2 3 4 5 6 7 8
| 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对象
1 2 3 4 5 6
| 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
将结果集的每一行,封装到对象数组中
1 2 3 4 5 6 7 8 9 10 11
| 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[]
1 2 3 4 5 6 7 8 9
| 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); } } }
|