sqlite_prepare_v2不返回SQLITE_OK

时间:2013-08-15 13:36:26

标签: objective-c database sqlite prepare

我一直在努力将高分数保存到数据库中并且在过去的一周内一直失败,我不知道为什么它不起作用。我一直收到“准备声明问题”,并拒绝将信息插入数据库。我已经检查过数据库管理器以确保没有sql语句的拼写错误,并且当在管理器上运行查询时,它工作正常 - 它只是给我问题的iphone。如果有人可以请快速查看并看到它有问题并且可以让我知道,我会非常感激!

- (NSMutableArray *) saveLocal {
    NSLog(@"save local database");
    @try {
        [self checkDB];
        sqlite3_stmt *sqlStatement2;


        NSString *sqlS = [NSString stringWithFormat:@"INSERT INTO localHighscore (difficulty, score, uname, puzzles, multiplier, oneshots, hints) VALUES (%i,%i,\"%@\",%i,%i,%i,%i)",[[MySingleton sharedMySingleton] goDifficulty],[[MySingleton sharedMySingleton] goScore],_player, [[MySingleton sharedMySingleton] goPuzzles], [[MySingleton sharedMySingleton] goMultiplier], [[MySingleton sharedMySingleton] goOneshots], [[MySingleton sharedMySingleton] goHints]];
        NSLog(@"%@",sqlS);
        const char *sql = [sqlS UTF8String];


        if(sqlite3_prepare_v2(localHighscore, sql, -1, &sqlStatement2, NULL) == SQLITE_OK)
        {
            sqlite3_step(sqlStatement2);
            sqlite3_reset(sqlStatement2);
            sqlite3_finalize(sqlStatement2);
            NSLog(@"save complete");
        } else {
            NSLog(@"Problem with prepare statement");
        }  
        sqlite3_close(localHighscore);
    }@catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }@finally{
        NSLog(@"DB Loaded!");
    }
}

这里是checkDB方法,它检查数据库是否存在,如果不存在则创建一个

- (void)checkDB {
    NSString *docsDir;
    NSArray *dirPaths;

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"localHighscore.sqlite"]];

    NSFileManager *filemgr = [NSFileManager defaultManager];    
    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
    const char *dbpath = [databasePath UTF8String];
        NSLog(@"file was not found");
        if (sqlite3_open(dbpath, &localHighscore) == SQLITE_OK)
        {
            NSLog(@"db open");
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS localHighscore(pk INTEGER PRIMARY KEY AUTOINCREMENT, difficulty TINYINT, score MEDIUMINT, uname VARCHAR(255), puzzles TINYINT, multiplier TINYINT, oneshots TINYINT, hints TINYINT)";

            if (sqlite3_exec(localHighscore, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"Failed to create table");
            }
            sqlite3_close(localHighscore);            
        } else {
            NSLog(@"Failed to open/create database");
        }
    }
    [filemgr release];
}

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

有几点想法:

  1. 在尝试使用数据库之前,您似乎没有调用sqlite3_open

  2. 每当出现错误时,您应该查看sqlite3_errmsg,例如

    if (sqlite3_exec(localHighscore, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
    {
        NSLog(@"Failed to create table: %s", sqlite3_errmsg(localHighscore));
    }
    
  3. 可能与您的问题无关,但您通常不应使用stringWithFormat构建SQL语句(至少如果您有任何文本字段)。在SQL中使用?占位符,然后使用sqlite3_bind_xxx函数。

    const char *sql = "INSERT INTO localHighscore (difficulty, score, uname, puzzles, multiplier, oneshots, hints) VALUES (?,?,?,?,?,?,?)";
    
    if(sqlite3_prepare_v2(localHighscore, sql, -1, &sqlStatement2, NULL) == SQLITE_OK)
    {
        if (sqlite3_bind_int(sqlStatement2, 1, [[MySingleton sharedMySingleton] goDifficulty]) != SQLITE_OK) {
            NSLog(@"bind 1 failed: %s", sqlite3_errmsg(localHighscore));
        }
    
        if (sqlite3_bind_int(sqlStatement2, 2, [[MySingleton sharedMySingleton] goScore]) != SQLITE_OK) {
            NSLog(@"bind 2 failed: %s", sqlite3_errmsg(localHighscore));
        }
    
        if (sqlite3_bind_text(sqlStatement2, 3, [_player UTF8String], -1, NULL) != SQLITE_OK) {
            NSLog(@"bind 3 failed: %s", sqlite3_errmsg(localHighscore));
        }
    
        // repeat this bind process for each variable
    
        if (sqlite3_step(sqlStatement2) != SQLITE_DONE) {
            NSLog(@"step failed: %s", sqlite3_errmsg(localHighscore));
        }
    
        // reset not needed (doesn't hurt, but not needed unless you're going to re-use it
        // sqlite3_reset(sqlStatement2);
    
        sqlite3_finalize(sqlStatement2);
        NSLog(@"save complete");
    } else {
        NSLog(@"Problem with prepare statement: %s", sqlite3_errmsg(localHighscore));
    }  
    sqlite3_close(localHighscore);
    

    如果您觉得这种语法不实用,那么可以考虑使用FMDB,这样可以简化您的SQL交互。但要谨慎使用SQL stringWithFormat(如果插入的字符串有引号,sqlite3_prepare将失败,理论上,您的应用程序会受到SQL注入攻击等)。

  4. 顺便说一句,你不应该[filemgr release],因为你不拥有它。

答案 1 :(得分:0)

我看到,当SQL语句包含“ booleanfield = false”而不是“ booleanfield = 0”之类的条件时,“ sqlite3_prepare_v2()”函数会返回“通用错误”(错误代码= 1)。在SQLiteStudio程序的SQL框中执行的同一条SQL语句使用了比较的第一种或第二种形式就可以得到良好的结果。