查询数据库数据使用HashMap保存

博客内容描述了在查询数据库后使用HashMap保存数据时遇到的问题。原本的代码会导致只保存最后一条数据,通过将Map初始化移到while循环内部解决了这个问题,从而成功保存所有查询结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 public List<Map<String, Object>> findsousuosearch(String search) {
  List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
  Map<String, Object> map = new HashMap<String, Object>();
  Cursor cursor = db.rawQuery("SELECT pm.id,pm.cname,pm.cname_pywb,pm.spunit,pm.price," +
    "pmo.photo,pmo.comment FROM posbase_menu as pm,posbase_menu_ole as pmo where pmo.masterid=pm.id and pm.cname_pywb like 'B%'",null);
  while (cursor.moveToNext()) { 
   int id  =cursor.getInt(cursor.getColumnIndex("id"));
   String cname = cursor.getString(cursor.getColumnIndex("cname"));
   String cname_pywb = cursor.getString(cursor.getColumnIndex("cname_pywb"));
   String spunit = cursor.getString(cursor.getColumnIndex("spunit"));
   int price=cursor.getInt(cursor.getColumnIndex("price"));
   byte[] photo  =cursor.getBlob(cursor.getColumnIndex("photo"));
    String comment=cursor.getString(cursor.getColumnIndex("comment"));
     map.put("backimg", id);
   map.put("cname", cname);
   map.put("cname_pywb", cname_pywb);
   map.put("spunit", spunit);
   map.put("price", price);
   map.put("photo", photo);
   map.put("comment", comment);
   list.add(map);
  }
  cursor.close();
  return list;
 }

但是查询的时候获取的就是最后一条添加的数据

我不知道错在了哪里。。

然后我又从网上查了一下 设置map初始化的时候我放在了最外面

然后我是这样设置的

public List<Map<String, Object>> findsousuosearch(String search) {
  List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
  Map<String, Object> map = null;
  Cursor cursor = db.rawQuery("SELECT pm.id,pm.cname,pm.cname_pywb,pm.spunit,pm.price," +
    "pmo.photo,pmo.comment FROM posbase_menu as pm,posbase_menu_ole as pmo where pmo.masterid=pm.id and pm.cname_pywb like 'B%'",null);
  while (cursor.moveToNext()) { 
   int id  =cursor.getInt(cursor.getColumnIndex("id"));
   String cname = cursor.getString(cursor.getColumnIndex("cname"));
   String cname_pywb = cursor.getString(cursor.getColumnIndex("cname_pywb"));
   String spunit = cursor.getString(cursor.getColumnIndex("spunit"));
   int price=cursor.getInt(cursor.getColumnIndex("price"));
   byte[] photo  =cursor.getBlob(cursor.getColumnIndex("photo"));
    String comment=cursor.getString(cursor.getColumnIndex("comment"));
   map=new HashMap<String, Object>();
   map.put("backimg", id);
   map.put("cname", cname);
   map.put("cname_pywb", cname_pywb);
   map.put("spunit", spunit);
   map.put("price", price);
   map.put("photo", photo);
   map.put("comment", comment);
   list.add(map);
  }
  cursor.close();
  return list;
 }

把map初始化放在while里面 就可以了,

这样就保存了所有的数据了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值