moveToFirst的SQLitedatabase函数

时间:2013-09-09 18:22:23

标签: java android mysql sql sqlite

我在数据库中插入了一些值,并使用insertId查询了一个游标,我从database.insert命令得到了数据集但是我没有得到cursor.moveToFirst()的函数,为什么我要调用它?在调用它之后,我能够在某个对象中获取插入的值!!

 long insertId = database.insert(MySQLiteHelper.TABLE_NAME, null,
        values);

   Cursor cursor = database.query(MySQLiteHelper.TABLE_NAME,
        allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
        null, null, null);
    cursor.moveToFirst();
 Message newMessage = cursorToMessage(cursor);
    cursor.close();

2 个答案:

答案 0 :(得分:2)

光标指向您的数据。起初它没有任何意义,所以你必须致电moveToFirst()。如果你得到多个结果,你可以在while循环中调用moveToNext(),只要有结果,循环就会继续。

答案 1 :(得分:1)

这是迭代每个步骤中游标可能内容的所有可能值的一种方法:

Cursor cursor = //Reference to whatever cursor you have...
        if(cursor != null && !cursor.isAfterLast() && !cursor.isClosed()){
                //this method positions the cursor always in the first item, since there's not warranty is pointing to it...
            cursor.moveToFirst();
            do{
                //Here you have the chance to create your transfer data object and populat it with the column values...
                String column = cursor.getString(cursor.getColumnIndex("columnName"));
            }
                //Here we go to the next element in cursor IF any...
            while(cursor.moveToNext());
            cursor.close();
        }

希望这有帮助。

问候!