0

我创建了一个目前只有一个表的 SQLite 数据库。我将它连接到 Xcode,完成了所有必需的步骤,并在编写文件时发现了问题。

我的表有 5 个项目(主键、姓名、出生日期、大学名称、课程名称)。

在保存我的数据时,它说:

由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“创建添加语句时出错。'乱序调用的库例程''

我设置了断点并找到了问题所在,但我无法解决它。

-(void)saveStudentInfo{

sqlite3_stmt *statement = NULL;


    const char *sql = "insert into studentInfo (name,collegeName,courseName) Values (?, ?, ?)";

    if (sqlite3_open("my_db_filename.db", &database) == SQLITE_OK)
    {
        //sqlite3_stmt *addStmt;

        if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
        {
            NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
        } else {
            // do things with addStmt, call sqlite3_step
            sqlite3_bind_text(addStmt, 1, [studentName UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(addStmt, 3, [studentCollegeName UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(addStmt, 4, [studentCourseName UTF8String], -1, SQLITE_TRANSIENT);

            if(SQLITE_DONE != sqlite3_step(addStmt))
                NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
            else
                studentID = sqlite3_last_insert_rowid(database);

            sqlite3_finalize(statement);
        }
        sqlite3_close(database);     
    }


if (sqlite3_step(statement)==SQLITE_DONE){
    UIAlertView *error = [[UIAlertView alloc]initWithTitle:@"Done" message:@"Files were added to database" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
    [error show];
}
else {
    UIAlertView *error = [[UIAlertView alloc]initWithTitle:@"Error" message:@"StudentOrganizer could not add database" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
    [error show];
}
4

1 回答 1

1

我想你在调用 sqlite3_prepare_v2 之前忘记打开数据库了。

一个很好的方法是这样的:

sqlite3* database;
if (sqlite3_open("my_db_filename.db", &database) == SQLITE_OK)
{
    sqlite3_stmt *addStmt;

    if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
    {
        NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
    } else {
        // do things with addStmt, call sqlite3_step
        sqlite3_finalize(sqlStatement);
    }
    sqlite3_close(database);     
}
于 2012-10-02T17:45:05.873 回答