在SQLite3中插入多行

时间:2012-11-04 15:07:23

标签: ios xcode sqlite

如何以编程方式将多行插入到iOS的sqlite3表中?这是我当前方法的代码片段:

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);

这样我只会插入第一行,如何告诉sqlite我希望每个'for'循环都是行插入?我找不到任何这样的例子......

谢谢!

2 个答案:

答案 0 :(得分:1)

您必须运行此声明:

sqlite3_step(compiledStatement) == SQLITE_DONE

每次插入后,在您的代码中,我看到您最后只运行一次。

答案 1 :(得分:1)

我得到了它,现在是我的代码:

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);