数据库查询结果Cursor,怎样准确地给model准确赋值

Android软件开发,在查询数据库的时候,经常使用db.execQuery(String sql)执行一句数据库语句,结果返回的是Cursor,cursor包含了要查询的结果所有符合条件的字段名和对应的值,那么怎样准确的利用cursor把值取出来呢。

*cursor的方法getString(int index),getInt(int index)等等获取相应数据类型。调试的时候,发现cursor结果字段集合中每个字段都有对应的下标,那么利用下标不就可以取到值了。然后就犯了一个错误,对于熟悉使用cursor的人来说,是个很低级的错误,我把调试结果中每个字段对应的下标写死了,,,是的,写死了!*

上代码:

Cursor cursor = null;
        try {
            cursor = db.execQuery("select * from noticeTB ORDER BY time desc limit "+ pg*cnt +","+ cnt);
            List<NoticeEntity> notice = new ArrayList<>();
            if(cursor!=null){
                while (cursor.moveToNext()){
                    NoticeEntity entity = new NoticeEntity();
                    entity.setName(cursor.getString(1));
                    entity.setType(cursor.getInt(3));
                    entity.setTime(cursor.getLong(2));
                    entity.setPhone(cursor.getString(4));
                    notice.add(entity);
                }
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

然后运行,结果没问题啊,可以当我换个测试机后,就发现问题了,取到的值乱了,比如代码中我有两个String类型的值,结果就是人名显示成手机号,手机号显示成人名。呵呵哒了~再调试就发现了问题的所在。

在不同手机上,查询出来的结果,cursor中的字段顺序可能不一样的,所以在设置相关数据的时候,就不能把下标写死,比如:

entity.setName(cursor.getString(2));

这样在别的手机上可能出来的结果就不一样了,下标就可能不是2而是其他的,那么怎么确定字段的下标呢,cursor有个方法getColumnIndex(“字段名”),调用这个方法就可以获得字段在查询结果中的下标了:

entity.setName(cursor.getString(cursor.getColumnIndex("name")));

代码示例

Cursor cursor = null;
        try {
            cursor = db.execQuery("select * from noticeTB ORDER BY time desc limit "+ pg*cnt +","+ cnt);
            List<NoticeEntity> notice = new ArrayList<>();
            if(cursor!=null){
                while (cursor.moveToNext()){
                    NoticeEntity entity = new NoticeEntity();
                    entity.setName(cursor.getString(cursor.getColumnIndex("name")));
                    entity.setType(cursor.getInt(cursor.getColumnIndex("type")));
                    entity.setTime(cursor.getLong(cursor.getColumnIndex("time")));
                    entity.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
                    notice.add(entity);
                }
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

希望和我以一样的菜鸟们引以为戒吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值