- 使用ColumnListHandler
public static void columnListHandler() throws SQLException { Connection con = MyJDBCUtiles.getConnection(); QueryRunner qr = new QueryRunner(); String sql = "select username,password from userinfo where age = ?"; //注意sql语句中的筛选项(username,password)一定要包括下列list中的参数项(username) Object [] param = {29}; List<Object> list = qr.query(con,sql,new ColumnListHandler<Object>("username"),param); //若没有查询到则list.size()=0 for (Object o : list){ System.out.println(o + " "); }
}
- 结果
- 使用ScalarHandler
public static void scalarHandler() throws SQLException { Connection con = MyJDBCUtiles.getConnection(); String sql = "select count(*) from userinfo where age = ?"; QueryRunner qr = new QueryRunner(); Object [] param = {21}; long o = qr.query(con,sql,new ScalarHandler<Long>(),param); //若未查询到,则o的值为0 System.out.println(o);
}
- 结果
- 使用MapHandler
Map<键,值>:键为列名,值为列的属性值
public static void mapHandler() throws SQLException { Connection con = MyJDBCUtiles.getConnection(); String sql = "select * from userinfo where age = ?"; Object[] param = {21}; QueryRunner qr = new QueryRunner(); Map<String,Object> map = qr.query(con,sql,new MapHandler(),param); for(String key : map.keySet()){ System.out.println(key+">>>"+map.get(key)); }
}
- 结果
-
使用MapListHandler
public static void mapListHandler() throws SQLException { Connection con = MyJDBCUtiles.getConnection(); String sql = "select * from userinfo where age = ?"; Object[] param = {21}; QueryRunner qr = new QueryRunner(); List<Map<String,Object>> list = qr.query(con,sql,new MapListHandler(),param); for(Map<String,Object> map : list){ for(String key : map.keySet()){ System.out.print(key+":"+map.get(key)+" "); } System.out.println(); }
}
- 结果
^_^