【问题标题】:SQLite 3 C API TransactionsSQLite 3 C API 事务
【发布时间】:2009-01-06 15:19:07
【问题描述】:

我正在使用 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 吗?感谢您的帮助。

【问题讨论】:

    标签: database sqlite transactions


    【解决方案1】:

    使用以下方式开始事务:sqlite3_exec(db, "BEGIN", 0, 0, 0);

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

    【讨论】:

    • 你会认为会有一个更干净的 API 来解决这个问题......为什么他们不只包含一个 sqlite3_exec_trans_begin(db) 调用......
    • 如果同时访问数据库文件,sqlite3_exec(db, "BEGIN", 0, 0, 0); 是否会失败?
    • @afriza,BEGIN 是一个延迟操作。延迟意味着在第一次访问数据库之前不会在数据库上获取锁。因此,对于延迟事务,BEGIN 语句本身对文件系统没有任何作用。在第一次读取或写入操作之前不会获取锁。请参阅 sqlite.org/lang_transaction.html 了解 BEGIN 的其他尝试获取锁的变体。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2014-11-21
    • 2012-06-24
    相关资源
    最近更新 更多