rawQuery返回总是返回false

时间:2011-10-26 12:21:44

标签: android sqlite android-sdk-2.1

我正在尝试迭代我的数据库记录。但由于某种原因,它总是返回一个空光标。 如果我从模拟器中取出数据库文件文件'File explorer tab',我可以看到表格及其中的数据。

这是我的代码:

Cursor result = db.getReadableDatabase().rawQuery(
                    "SELECT _ID, STUDENT_NAME, STUDENT_GRADE, STUDENT_ADDRESS "
                            + "FROM students", null);
            while (!result.moveToNext())
            {
                int id = result.getInt(0);
                String studentName = result.getString(1);
                String studentGrade = result.getString(2);
                String studentAddress = result.getString(3);
                Log.d("Sqlitedemo", "ID=" + id + ", STUDENT_NAME=" + studentName +", STUDENT_GRADE="+studentGrade+", STUDENT_ADDRESS="+studentAddress);
            }
            result.close();

现在while(!result.moveToNext())总是返回false。

这是我的DatabaseHelper类:

public class DatabaseHelper extends SQLiteOpenHelper
{
    private static final String DATABASE_NAME   = "db";
    static final String         STUDENT_NAME    = " STUDENT_NAME";
    static final String         STUDENT_GRADE   = "STUDENT_GRADE";
    static final String         STUDENT_ADDRESS = "STUDENT_ADDRESS";

    public DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        // creating the table
        db
                .execSQL("CREATE TABLE students (_id INTEGER PRIMARY KEY AUTOINCREMENT, STUDENT_NAME TEXT, STUDENT_GRADE TEXT,  STUDENT_ADDRESS TEXT);");

        ContentValues cv = new ContentValues();

        cv.put(STUDENT_NAME, "Roi");
        cv.put(STUDENT_GRADE, "85");
        cv.put(STUDENT_ADDRESS, "Tel aviv");

        db.insert("students", STUDENT_NAME, cv);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // TODO Auto-generated method stub

    }

}

任何想法?

谢谢, 射线。

2 个答案:

答案 0 :(得分:4)

Cursor result = db.getReadableDatabase().rawQuery(
                "SELECT _ID, STUDENT_NAME, STUDENT_GRADE, STUDENT_ADDRESS "
                        + "FROM students", null);
int id = result.getInt(0);
String studentName = result.getString(1);
String studentGrade = result.getString(2);
String studentAddress = result.getString(3);
if (result.moveToFirst())
{
    Log.d("Sqlitedemo", "ID=" + id + ", STUDENT_NAME=" + studentName +", STUDENT_GRADE="+studentGrade+", STUDENT_ADDRESS="+studentAddress);
    while(result.moveToNext())
    {
        Log.d("Sqlitedemo", "ID=" + id + ", STUDENT_NAME=" + studentName +", STUDENT_GRADE="+studentGrade+", STUDENT_ADDRESS="+studentAddress);
    }
}
result.close();

答案 1 :(得分:2)

  while (!result.moveToNext())

删除!,它会神奇地开始工作。您当前的代码是“虽然没有更多结果......”