开发者

SQLite iPhone - Insert Fails

开发者 https://www.devze.com 2023-01-04 16:32 出处:网络
I am trying to insert a value to a SQLite db, but everytime I try my program simply crashes with no error message at all.

I am trying to insert a value to a SQLite db, but everytime I try my program simply crashes with no error message at all.

Here is my code:

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

    // The Database is stoed in the application bundle
    NSArray *paths = NSSearchPathForDirectories开发者_JS百科InDomains(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));
    }

}

The error seems to occur on the bind statement. I have confirmed the database is actually being opened, and refname is correctly being passed to my method.

Can anyone help? I would normally use core data, however this is a bug fix to an existing project, and I simply do not have the time to allocate to making the move to core data.


The order of your statements is incorrect. bind_() is used after prepare() SQLite bind() documentation

The first argument to the sqlite3_bind_*() routines is always a pointer to the sqlite3_stmt object returned from sqlite3_prepare_v2() or its variants.

    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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号