0

我正在尝试在 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 会以时间戳存储在数据库中的动作中。我只需要知道为什么我的查询不起作用,如果我做一个简单的计数,我会得到正确的行数。

这是我将胜利插入数据库的代码:

-(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,但这似乎并不重要,因为更简单的查询仍然有效。

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

干杯

4

1 回答 1

1

我得到它:

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

实际上是一样的SELECT COUNT(*) FROM Wins WHERE Action='Win'

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

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

就是你要找的!

于 2013-10-21T10:30:57.457 回答