vendredi 9 octobre 2015

SQLite Batch execute queries using transaction in iOS

I have an array of strings, which are a bunch of different queries, some are insert, some are update, etc. These are all stored in the variable insertQueries

This is what I have so far, nothing is actually being inserted, I just found out about SQL Transactions today, so I may not be doing this properly, if somebody can guide me on what I could be doing wrong, or any further improvements can be made to speed up the process, it would be greatly appreciated!

int completed = 0;

    sqlite3_exec(database, "BEGIN TRANSACTION", 0, 0, 0);

    BOOL hasError;

    //Loop through insert queries
    for (int i = 0; i < [insertQueries count]; i++) {
        //Grab insert statement
        const char *sql_stmt = [[insertQueries objectAtIndex:i] UTF8String];

        if (sqlite3_prepare_v2(database, sql_stmt, -1, &compiledStatement, NULL) == SQLITE_OK) {
            if (sqlite3_step(compiledStatement) != SQLITE_DONE) {
                hasError = YES;

                NSLog(@"Error %s", sqlite3_errmsg(database));
            }
        }

        NSLog(@"Finished query: %i", completed);
        completed++;

        //Finalize statement
        sqlite3_finalize(compiledStatement);
    }

    //If no errors, commit
    if (hasError) {
        sqlite3_exec(database, "COMMIT", 0, 0, 0);
    } else {
        sqlite3_exec(database, "ROLLBACK", 0, 0, 0);
    }

    //Close database
    sqlite3_close(database);

Aucun commentaire:

Enregistrer un commentaire