4

我将数据保存在我的 SQL 数据库中。

现在我想将保存的数据与字符串进行比较

像这样的东西:

String example = "house";

现在我想用 if 子句检查“房子”是否已经在数据库中

像这样的东西

if ( example == [SQL Data] ) {
}
else {
}

现在,我怎样才能做到这一点?

4

4 回答 4

10

做类似的事情

String sql = "SELECT * FROM your_table WHERE your_column = '" + example + "'";
Cursor data = database.rawQuery(sql, null);

if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}

从这里偷来的

于 2012-10-16T17:39:20.613 回答
1

写下我对 Sharath 评论的回复作为答案,因为代码会在评论中搞砸:

并不是说您的回答是错误的,但是从表中选择所有内容并在数据库之外对其进行迭代确实效率低下,并且不应该建议将其作为问题的答案,因为这样做通常是一个坏习惯。

我通常这样做的方式,如果我想查看数据库中是否存在某些记录,我确实喜欢这样。不会争论在正常的while循环上使用do-while,因为那是关于不同的偏好;)

String query = "SELECT * FROM table_name WHERE column_name=" + the_example_string_to_find;              
Cursor cursor = db.rawQuery(query, null);

if(cursor.getCount() > 0) {
    cursor.moveToFirst();
    while(!cursor.isAfterLast()) {
        // Do whatever you like with the result.
        cursor.moveToNext();
    }
}
于 2012-10-16T17:39:55.473 回答
1
// Getting Specific  Record by name. 
// in DB handler class make this function call it by sending search criteria. 
    Records getRecord(String name) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID, KEY_NAME, KEY_Auth_Name, KEY_B_PRICE}, KEY_ID + "=?",
                new String[]{name}, null, null, null,null);
        if (cursor.getCount() > 0)
            cursor.moveToFirst();
        Records Records = new Records(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return book
        return Records;
    }
于 2017-04-23T17:18:31.550 回答
0

您需要首先从数据库中获取所有数据,然后使用从数据库中获得的数据检查数据。

查看链接示例数据库示例

假设您从数据库中获得了一个游标对象

cursor = db.rawQuery("SELECT yourColumnName FROM "+TABLE_NAME, null);
if(!cursor.moveToFirst()){

 }
 else{

do {
if(cursor.getString(0).equals(example)) 
 //do something which you want and break
 break;
 } while (cursor.moveToNext());

 }
于 2012-10-16T17:02:29.867 回答