List<Map<String,String>>
有时候连接数据库查询结果可能为List<Map<String,String>>类型。我们先来看下代码。
public static List< Map<String,String> > show(String sql, String[] params){
// String sql ="select * from employee";
List< Map<String,String> > listmap = new ArrayList<>();
DBConnection db = new DBConnection();
ResultSet rs = null;
try {
Statement stmt = (Statement) db.conn.createStatement();
rs = (ResultSet) stmt.executeQuery(sql);
while(rs.next()){
Map<String,String> map = new HashMap<String,String>();
for(int i = 0; i < params.length; i++) {
map.put(params[i], rs.getString(params[i]));
}
listmap.add(map);
}
rs.close();
db.close();//关闭连接
} catch (SQLException e) {
e.printStackTrace();
}
return listmap;
}
DBConnection为封装的连接数据库的类函数。
返回值:List<Map<String,String>>类型。返回查询的结果。
参数:sql是sql语句。这里是查询代码。[]params是要查询的数据库的字段名(列)。
rs返回查询数据库之后的结果集。
一遍for循环查询一个记录。然后遍历整个结果集rs,放在listmap中。
来看下函数调用
String sel="select * from t_student";
List< Map<String,String> > data = MysqlUtil.show(sel, MysqlConfig.userinfo);
System.out.println("name:" + data.get(1).get("name"));
来看下删除第二个get的效果。
总结:以list<map<string,string>>类型为返回值的类型。可以通过get方法获取数据库对应的数据。
这种比不上c#的返回值。因为这种结果返回值是通过链式查询的,而c#返回值是集合。查找会高效一些。