iOS - 提高插入性能SQLite

时间:2015-12-22 07:25:44

标签: ios objective-c sqlite

如何在SQLite数据库中提高性能插入数据。

数据量为30000条记录。守则是:

- (void)insertBranchDB:branchlistArray
{
const char *dbpath = [databasePath UTF8String];

if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
    int count = 0;
    for (Branch *branch in branchlistArray) {
        NSString *insertSQL = [NSString stringWithFormat:
                               @"insert or replace into Branch (id, lang, lat, lng, province_id, district_id, optional, bus, status, name, address, contact, telephone, remark, province_name, district_name, lastupdate) values (\"%@\", \"%@\", \"%@\", \"%@\",\"%@\", \"%@\", \"%@\", \"%@\",\"%@\", \"%@\", \"%@\", \"%@\",\"%@\", \"%@\", \"%@\", \"%@\", \"%@\")",branch._id,branch.lang,branch.lat,branch.lng,branch.province_id,branch.district_id,branch.optional,branch.bus,branch.status,branch.name,branch.address,branch.contact,branch.telephone,branch.remark,branch.province_name,branch.district_name,branch.lastupdate];
        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE) {
            NSLog(@"Completed to Add Branch %d",count);
            count;
        }
        else {
            NSLog(@"Failed to Add Branch %d",count);
            count;
        }
    }
    sqlite3_finalize(statement);
    sqlite3_close(database);
    }
}

2 个答案:

答案 0 :(得分:1)

如果您使用交易,您会看到显着的性能提升。因此,在执行所有INSERT语句之前,请执行BEGIN TRANSACTION,最后执行COMMIT(或COMMIT TRANSACTIONEND TRANSACTION)。

请参阅Transactions上的http://sqlite.org讨论。

答案 1 :(得分:-2)

查看批量插入行

INSERT INTO 'tablename'
SELECT 'data1' AS 'column1', 'data2' AS 'column2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'

所以在你的情况下:

INSERT INTO 'Branch'
SELECT 'id' AS 'column1', 'lang' AS 'column2'
UNION ALL SELECT 'row_one_.branch._id', 'row_one_.branch.lang'
UNION ALL SELECT 'row_two_.branch._id', 'row_two_.branch.lang'
UNION ALL SELECT 'row_three_.branch._id', 'row_three_.branch.lang'

查看此帖子Is it possible to insert multiple rows at a time in an SQLite database?