Andr Devs
Andr Devs

Reputation: 215

Inserting multiple rows in SQLite3

How could I programmatically insert several rows into an sqlite3 table for iOS? This is a code snippet of my current method:

sqlite3 *database;

if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
    const char *sqlStatement = "insert into TestTable (id, colorId) VALUES (?, ?)";
    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
    {
        for (int i = 0; i < colorsArray.count; i++) {
            sqlite3_bind_int(compiledStatement, 1, elementId);
            long element = [[colorsArray objectAtIndex:i] longValue];
            sqlite3_bind_int64(compiledStatement, 2, element);
        }
    }

    if(sqlite3_step(compiledStatement) == SQLITE_DONE) {
        sqlite3_finalize(compiledStatement);
    }
    else {
        NSLog(@"%d",sqlite3_step(compiledStatement));
    }
}
sqlite3_close(database);

This way I only get the first row inserted, how can I tell sqlite that I want each 'for' loop to be a row insertion? I couldn't find any example of this...

Thanks!

Upvotes: 2

Views: 4036

Answers (2)

Andr Devs
Andr Devs

Reputation: 215

I got it working, this is now my code:

sqlite3 *database;

if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
    const char *sqlStatement = "insert into TestTable (id, colorId) VALUES (?, ?)";
    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
    {
        for (int i = 0; i < colorsArray.count; i++) {
            sqlite3_bind_int(compiledStatement, 1, elementId);
            long element = [[colorsArray objectAtIndex:i] longValue];
            sqlite3_bind_int64(compiledStatement, 2, element);

            if (sqlite3_step(compiledStatement) == SQLITE_DONE) {
                if (i == (colorsArray.count - 1))
                    sqlite3_finalize(compiledStatement);
                else
                    sqlite3_reset(compiledStatement);
            }
            else {
                NSLog(@"row insertion error");
            }
        }
    }
}
sqlite3_close(database);

Upvotes: 1

edzio27
edzio27

Reputation: 4140

You have to run this statement:

sqlite3_step(compiledStatement) == SQLITE_DONE

after each insertion, and in your code i see that you run it only once, on the end.

Upvotes: 1

Related Questions