检查 SQLite Android 中是否存在数据 [英] Check if data is exist in SQLite Android

查看:57
本文介绍了检查 SQLite Android 中是否存在数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此函数从 SQlite 获取特定数据:

I use this function to get specific data from SQlite:

SearchRes getSresultByName(String name) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
            KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
            new String[] { name }, null, null, null, null);

    if (cursor != null)
        cursor.moveToFirst();

    SearchRes searchres = new SearchRes(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2));

    return searchres;
}

它工作得很好,我需要创建类似的函数来测试表中是否存在值,所以我尝试了这个:

And it works just fine, I need to create similar function to test if value is exist in the table, so I tried this:

boolean checkIfExist(String name) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
            KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
            new String[] { name }, null, null, null, null);


    if (cursor == null)
        return false;

    else
        return true;

}

但我总是得到正确的.你能帮我找出问题所在吗?

But I always get TRUE. Can you help me figure out what is the problem?

推荐答案

你不应该检查游标是否为空 你应该检查游标中是否存在任何东西

you should not be checking if cursor is null you should be checking if anything exists in the cursor

if(cursor.moveToFirst()){
    return true
}else{
    return false;
}

这篇关于检查 SQLite Android 中是否存在数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆