sqlite with where子句不起作用

时间:2015-01-10 10:25:32

标签: android sqlite

以下是我的代码段。 我的查询确实返回单个值,但我不知道如何提取该值。 showtoast(ID)没有显示任何内容。请帮忙

try {
    String ID = null;
    mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
    Cursor allrows = mydb.rawQuery(
        "SELECT REGID FROM " + TABLE + " where NAME = '" + name_from_spinner + "'" ,
        null
    );

    if (allrows.moveToFirst()) {
        showToast("not empty");
        ID = allrows.getString(0);
        showToast(ID);
    } else {
        showToast("empty");
    }

    allrows.close();
    mydb.close();
} catch (Exception e) {
    Toast.makeText(
        getApplicationContext(),
        "Error encountered.",
        Toast.LENGTH_LONG
    );
}

1 个答案:

答案 0 :(得分:1)

永远不会从rawQuery获得空标记。而是使用moveToFirst

if (allrows.moveToFirst()) {
    showToast("not empty");
    ID = allrows.getString(0);
    showToast(ID);
}

此外,由于您只选择1列,因此您知道它的索引将为0。

如果您希望收到多个列,可以像这样循环光标:

if (allrows.getCount() == 0) {
    showToast("empty");
} else {
    while (allrows.moveToNext()) {
        ID = allrows.getString(0);
        showToast(ID);
    }
}
相关问题