SQLite其中字段类似于文本查询

时间:2013-10-21 08:39:21

标签: sqlite

我正在尝试在xcode中对我的数据库运行查询,并且它仍然返回0,即使有5个条目。调用数据库的代码如下所示:

-(int)CountWins
{
    int count = 0;
    if (sqlite3_open([[self filepath] UTF8String], &_db) == SQLITE_OK) {
    const char* query1= "SELECT COUNT(*) FROM Wins WHERE (Action LIKE 'Win');";

    sqlite3_stmt *statement;

    if( sqlite3_prepare_v2(_db, query1, -1, &statement, NULL) == SQLITE_OK )
    {
        //Loop through all the returned rows (should be just one)
        while( sqlite3_step(statement) == SQLITE_ROW )
        {
            count = sqlite3_column_int(statement, 0);
        }
    }
    else
    {
        NSLog( @"Failed from sqlite3_prepare_v2. Error is:  %s", sqlite3_errmsg(_db) );
    }

    // Finalize and close database.
    sqlite3_finalize(statement);
    //sqlite3_close(articlesDB);
    }
    [self closeDB];

    return count;
}

基本上,当用户赢得游戏时,Win会以时间戳存储在数据库中的操作中。所有我需要知道的是为什么我的查询不起作用,如果我做一个简单的计数我得到正确的行数。

以下是将win插入数据库的代码:

-(void) addwin
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];


    NSDate *TimestampVal = [NSDate date];
    NSString *actionVal = [NSString stringWithFormat:@"Win"];
    NSString *sqlstr = [NSString stringWithFormat:@"INSERT INTO 'Wins' ('Timestamp','Action') VALUES (?,?);"];

    sqlite3_stmt *statement;
    const char *str = [sqlstr UTF8String];

    if (sqlite3_prepare_v2(db, str, -1, &statement, NULL) == SQLITE_OK) {
        sqlite3_bind_text(statement, 1, [ [dateFormatter stringFromDate:TimestampVal] UTF8String],-1, NULL);
        sqlite3_bind_text(statement, 1, [actionVal UTF8String],-1, NULL);
    }

    if (sqlite3_step(statement) != SQLITE_DONE){
        NSAssert(0,@"Error Updating Table.");
    }
    sqlite3_finalize(statement);
}

我还尝试将此查询存储为字符串并转换为UTF8String,但这似乎并不重要,因为更简单的查询仍然有效。

任何帮助都会很棒,谢谢。

干杯

1 个答案:

答案 0 :(得分:1)

我明白了:

SELECT COUNT(*) FROM Wins WHERE (Action LIKE 'Win')

实际上与SELECT COUNT(*) FROM Wins WHERE Action='Win'相同。

如果您的标准是“包含单词获胜”,那么

SELECT COUNT(*) FROM Wins WHERE Action LIKE '%Win%'

正是您要找的!