SQLite iPhone - 插入失败

时间:2010-06-26 14:03:46

标签: iphone sqlite insert

我正在尝试向SQLite数据库插入一个值,但每次尝试我的程序时都会崩溃而根本没有错误消息。

这是我的代码:

- (void) insertToDatabase:(NSString *) refName {

    // The Database is stoed in the application bundle
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"staticdata.sqlite"];

    if(sqlite3_open([path UTF8String], &database) == SQLITE_OK){
        const char *sql = "Insert into usersDates(dateDescription) VALUES (?)";
        sqlite3_stmt *init_statement;
        sqlite3_bind_text(init_statement, 1, [refName UTF8String], -1, SQLITE_TRANSIENT);


        if(!sqlite3_prepare_v2(database, sql, -1, &init_statement, NULL) == SQLITE_OK){
            NSAssert1(0, @"Failed to insert to database file with message '%s'.", sqlite3_errmsg(database));
        }
        if(sqlite3_step(init_statement) != SQLITE_DONE ) {
            NSLog( @"Error: %s", sqlite3_errmsg(database) );
        } else {
            NSLog( @"Insert into row id = %d", sqlite3_last_insert_rowid(database));
        }

        sqlite3_finalize(init_statement);
    } else {
        sqlite3_close(database);
        NSAssert1(0, @"Failed to open database file with message '%s'.", sqlite3_errmsg(database));
    }

}

错误似乎发生在绑定语句中。我已经确认数据库实际上正在打开,并且refname正确传递给我的方法。

有人可以帮忙吗?我通常会使用核心数据,但这是对现有项目的错误修复,而我根本没有时间进行分配以转移到核心数据。

1 个答案:

答案 0 :(得分:2)

您的陈述顺序不正确。在bind_()之后使用prepare() SQLite bind() documentation

sqlite3_bind _ *()例程的第一个参数始终是指向sqlite3_prepare_v2()或其变体返回的sqlite3_stmt对象的指针。

    const char *sql = "Insert into usersDates(dateDescription) VALUES (?)";
    sqlite3_stmt *init_statement;

    if(!sqlite3_prepare_v2(database, sql, -1, &init_statement, NULL) == SQLITE_OK){
        NSAssert1(0, @"Failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
    }
    sqlite3_bind_text(init_statement, 1, [refName UTF8String], -1, SQLITE_TRANSIENT);

    sqlite_step(init_statement);