如何在android中的sqlite db中检查已经存在的值?

时间:2013-04-25 06:24:18

标签: android android-sqlite

在我的应用程序中,我在SQLite数据库中保存了一个帐号。在我添加新的帐单编号之前,如何检查数据库中是否存在帐单编号。

我的主要班级代码是,

 String bill_no_excist_or_not = db.billno_exist_or_not(""+et_bill_number.getText().toString());
 Log.v("Bill No", ""+bill_no_excist_or_not);

我的数据库代码,

String billno_exist_or_not(String bill_number){

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_BILL_DETAILS, new String[] { KEY_BILL_NUMBER }, KEY_BILL_NUMBER + "=?"
                    + new String[] { bill_number }, null, null, null, null);

//after this i don't know how to return the values

    return bill_number;
}

我不知道如何检查DB中已有或未有的值。任何人都知道请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

这个函数可以帮助您查找值是否在数据库中可用。

请在我的查询中替换您的查询..

public int isUserAvailable(int userId)
    {
        int number = 0;
        Cursor c = null;
        try
        {
            c = db.rawQuery("select user_id from user_table where user_id = ?", new String[] {String.valueOf(userId)});

            if(c.getCount() != 0)
                number = c.getCount();
        }
        catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(c!=null) c.close();
        }
        return number;
    }

答案 1 :(得分:1)

在表KEY_BILL_NUMBER中创建UNIQUE列,然后只需使用insertWithOnConflict标记SQLiteDatabase.CONFLICT_IGNORE

进行插入