SQLite 3 C API事务 [英] SQLite 3 C API Transactions

查看:215
本文介绍了SQLite 3 C API事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SQLite3 for iPhone开发,我试图将一些insert语句包装到一个事务中。目前我有下面的代码,这是工作正常但是阅读另一个问题后,我意识到,这将是更好的在一个事务,而不是每个。我找不到开始和提交事务的C API调用。一些代码是在Objective-C,但我不认为这真的相关的问题。

I am using SQLite3 for iPhone development and I'm attempting to wrap a few insert statements into a transaction. Currently I have the below code which is working properly however after reading another question on SO I realized it would be better to have these in one transaction rather than one each. I couldn't find the C API call to begin and commit a transaction. Some of the code is in Objective-C but I don't think that's really relevent to the question.

- (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吗?感谢您的帮助。

What I think needs to be done would be taking the sqlite3_prepare_v2 command out of the for loop, start the transaction, go through the for loop, commit the transaction. However, I'm not sure what the calls for "start the transaction" and "commit the transaction" are. And would I still use sqlite3_step? Thanks for your help.

推荐答案

开始一个事务: sqlite3_exec(db,BEGIN,0 ,0,0);

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

这篇关于SQLite 3 C API事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆