Cursor query详解

本文详细介绍了Android中SQLiteDatabase的rawQuery()方法的使用方法及其参数,并通过实例演示了如何执行SELECT语句及如何利用Cursor获取查询结果。此外,还列举了Cursor的主要方法及其用途。

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

 

 

 SQLiteDatabase的rawQuery()用于执行select语句,使用例子如下:

<a target=_blank href="http://www.iteedu.com/handset/android/sqlitediary/SQLiteDatabase.php"><span style="background-color: rgb(246, 246, 246);">SQLiteDatabase</span></a> db= ....;
<a target=_blank href="http://www.iteedu.com/handset/android/sqlitediary/Cursor.php"><span style="background-color: rgb(246, 246, 246);">Cursor</span></a> cursor = db.rawQuery("select * from person",null);
...
cursor.close();
db.close();

rawQuery()方法的第一个参数为select语句;第二个参数为select语句中占位符参数的值,如果select语句没有使用占位符,该参数可以设置为null。带占位符参数的select语句使用例子如下:

<a target=_blank href="http://www.iteedu.com/handset/android/sqlitediary/Cursor.php"><span style="background-color: rgb(246, 246, 246);">Cursor</span></a> cursor = db.rawQuery("select * from personwhere name like ?and age=?", new String

public Cursor query(String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String

having,String orderBy,String limit); 
参数说明: 
table:数据库表的名称 
columns:数据库列名称数组 写入后最后返回的Cursor中只能查到这里的列的内容 

selection:查询条件  

selectionArgs:查询结果  
groupBy:分组列 
having:分组条件 
orderBy:排序列 
limit:分页查询限制 
Cursor:返回值,将查询到的结果都存在Cursor 
 Cursor是一个游标接口,每次查询的结果都会保存在Cursor中 可以通过遍历Cursor的方法拿到当前查询到的所有信息。 
Cursor的方法 
moveToFirst() //将Curor的游标移动到第一条 
moveToLast()///将Curor的游标移动到最后一条 
move(int offset)//将Curor的游标移动到指定ID 
 moveToNext()//将Curor的游标移动到下一条 
moveToPrevious()//将Curor的游标移动到上一条 
getCount() //得到Cursor 总记录条数 
isFirst() //判断当前游标是否为第一条记录 
isLast()//判断当前游标是否为最后一条数据 
getInt(int columnIndex)    //根据列名称获得列索引ID 
 getString(int columnIndex)//根据索引ID 拿到表中存的字段 

例:读取一个集合的方法

public List<ChatMsgEntity> findMessList(String str,Integer start, Integer length) 
    { 
         List<ChatMsgEntity> jiluji = new ArrayList<ChatMsgEntity>(); 
      // 只对读的操作的方法
         SQLiteDatabase db = getReadableDatabase(); 
         String sql="select  * from "+str ;
         Cursor cursor = db.rawQuery(sql,null);
         cursor = db.query(str, null, null, null, null, null, null, null); 
       while (cursor.moveToNext()) 
       { 
       int useid = cursor.getInt(cursor.getColumnIndex("useid")); 
       String date = cursor.getString(cursor.getColumnIndex("date")); 
       String content = cursor.getString(cursor.getColumnIndex("content")); 
       int  fangxiang =cursor.getShort(cursor.getColumnIndex("dirr")); 
       boolean dirr;
       if(fangxiang%2 ==0)
        dirr=false;
       else
        dirr=true;
       jiluji.add(new ChatMsgEntity(useid, date, content,dirr));
       }

       cursor.close();
       db.close();
       return jiluji;
    } 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值