开发者

Insert into different tables in SQlite

I need to insert a bunch of data in an iPhone application but in different tables. The table name is in this data.

This is what I was trying to do:

    NSString *statement = @"insert into ? values (?, ?, 0)";
    sqlite3_stmt *compiledStatement;
    if(sqlite3_prepare_v2(database, [statement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
    {
        for(UpdateItems *item in updateData){
            sqlite3_bind_text(  compiledStatement, 1, [item.table UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(  compiledStatement, 2, [item.code UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(  co开发者_Python百科mpiledStatement, 3, [item.data UTF8String], -1, SQLITE_TRANSIENT);

            while(YES){
                NSInteger result = sqlite3_step(compiledStatement);
                if(result == SQLITE_DONE){
                    break;
                }
                else if(result != SQLITE_BUSY){
                    break;
                }
            }
            sqlite3_reset(compiledStatement);
        }
    } else  
        printf("db error: %s\n", sqlite3_errmsg(database)); 

    sqlite3_finalize(compiledStatement);
    sqlite3_close(database);

When running the above script I get the error: no such table: ? which is normal, as in sqlite3_prepare_v2 statement the data wasn't bind yet so SQLite doesn't know the table.

Now I will move the hole sqlite3_prepare_v2 block inside the loop and using stringWithFormat I will change the first question mark with the table name and after prepare it, but is there any other solution for this - more simple?


That is the simplest correct solution.

However there are performance benefits to not preparing queries each time. If performance is an issue then I would recommend creating a map from the table name to the prepared query. Then you only need to prepare the query the first time you encounter the table name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜