Cursor query理解

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的游标移动到上一条

public List<Zhangdan> query(){//查询所有的信息
        
        
        List<Zhangdan> list = new ArrayList<Zhangdan>();
        list.clear();//清空数据
        //查询全部数据
        Cursor cursor = db.rawQuery("select * from zhangdan" ,null);
       
        while(cursor.moveToNext()){
            int sum=0;
              int _id = cursor.getInt(cursor.getColumnIndex("_id"));
              String kongge1=cursor.getString(cursor.getColumnIndex("kongge1"));
              String fenlei = cursor.getString(cursor.getColumnIndex("fenlei"));//获取分类
              String kongge2=cursor.getString(cursor.getColumnIndex("kongge2"));
              String data = cursor.getString(cursor.getColumnIndex("data"));//获取日期
              String kongge3=cursor.getString(cursor.getColumnIndex("kongge3"));
            String num =  cursor.getString(cursor.getColumnIndex("num"));//获取金额
            int mon=Integer.parseInt(num);
            sum+=mon;
        String a=String.valueOf(_id)+kongge1+fenlei+kongge2+num+kongge3+data;
            System.out.print(sum);
            System.out.print(a);
            Zhangdan zd = new Zhangdan(String.valueOf(_id),kongge1,fenlei,kongge2,num,kongge3,data);
            
            list.add(zd);//将新对象添加到list集合
            
        }
                
                

 

posted @ 2022-05-30 17:03  zrswheart  阅读(104)  评论(0编辑  收藏  举报