我正在使用SQLite3进行iPhone开发,我试图将一些插入语句包装到一个事务中。目前我有以下代码正常工作但是在阅读了另一个关于SO的问题后,我意识到最好将这些问题放在一个事务中而不是每个事务中。我找不到C API调用来开始和提交事务。有些代码是在Objective-C中,但我认为这与问题无关。

- (void)saveAnimals {
    //Insert all the animals into the zoo database
    int i;

    const char *sql = "insert into Animal(Zoo_ID, Animal_Num, Animal_Text) Values(?, ?, ?)";
    for (i = 0; i < ([[self animalArray] count] - 1); i++) {

        if(addStmt == nil) {
            if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
                NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
        }
        int animalNum = [[[self animalArray] objectAtIndex:i] animal_Number];
        NSString *animalText = [[NSString alloc] initWithString:[[[self animalArray] objectAtIndex:i] animal_Text]];
        sqlite3_bind_int(addStmt, 1, zoo_ID);   
        sqlite3_bind_int(addStmt, 2, animalNum);    
        sqlite3_bind_text(addStmt, 3, [animalText UTF8String], -1, SQLITE_TRANSIENT);
        [animalText release];
        if(SQLITE_DONE != sqlite3_step(addStmt)) {
            NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
        }

        //Reset the add statement.
        sqlite3_reset(addStmt);     
    }
}

我认为需要做的是将sqlite3_prepare_v2命令从for循环中取出,启动事务,通过for循环,提交事务。但是,我不确定“开始交易”的要求是什么。和“提交交易”是。我还会使用sqlite3_step吗?谢谢你的帮助。

有帮助吗?

解决方案

使用以下命令启动事务: sqlite3_exec(db,&quot; BEGIN&quot;,0,0,0);

提交事务: sqlite3_exec(db,&quot; COMMIT&quot;,0,0,0);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top