【问题标题】:SQLite iPhone - Insert FailsSQLite iPhone - 插入失败
【发布时间】:2010-06-26 23:27:25
【问题描述】:

我正在尝试向 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 已正确传递给我的方法。

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

【问题讨论】:

    标签: iphone sqlite insert


    【解决方案1】:

    您的陈述顺序不正确。 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);
    

    【讨论】:

    • 谢谢,我刚刚想通了,回来回答我自己的问题。不过还是谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    相关资源
    最近更新 更多