我想插入数据库表中的2000行是否有任何方法可以非常快速地插入数据。我正在使用下面的代码在数据库中插入数据。
代码: -
+(NSString* )getDatabasePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Crocodilian"];
return writableDBPath;
}
+(NSMutableArray *)executeQuery:(NSString*)str{
sqlite3_stmt *statement= nil;
sqlite3 *database;
NSString *strPath = [self getDatabasePath];
NSMutableArray *allDataArray = [[NSMutableArray alloc] init];
if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) {
if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSInteger i = 0;
NSInteger iColumnCount = sqlite3_column_count(statement);
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
while (i< iColumnCount) {
NSString *str = [self encodedString:(const unsigned char*)sqlite3_column_text(statement, i)];
NSString *strFieldName = [self encodedString:(const unsigned char*)sqlite3_column_name(statement, i)];
[dict setObject:str forKey:strFieldName];
i++;
}
[allDataArray addObject:dict];
[dict release];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return allDataArray;
}
先谢谢。
答案 0 :(得分:2)
您的问题是,您尝试一次插入一行。 SQLite在每次插入后添加提交。插入大数据时,我遇到了类似的性能问题。我用批量插入解决了它。
首先使用多个插入创建查询(在这种情况下不需要预准备语句)并立即触发查询。这有很大的性能提升。唯一的问题是,您必须在创建多个插入查询之前验证数据。
快乐的编码..
答案 1 :(得分:2)
您可以尝试像批量插入一样
我的表格为Product(ProductID int,ProductName text,ShortDescription text)
sqlite3 *dtdb;
const char *dbpath=//database path
if ((sqlite3_open(dbpath,&dtdb)==SQLITE_OK))
{
sqlite3_exec(dtdb, "BEGIN TRANSACTION", NULL, NULL, &errorMessage);
char buffer[] = "INSERT INTO Product VALUES (?1, ?2, ?3)";
sqlite3_stmt* stmt;
sqlite3_prepare_v2(dtdb, buffer, strlen(buffer), &stmt, NULL);
for (unsigned i = 0; i < array.count; i++)
{
NSDictionary *dict=[array objectAtIndex:i];
NSArray *arKeys=[dict allKeys];
sqlite3_bind_int(stmt,1, [[dict objectForKey:@"ProductID"]intValue]);
sqlite3_bind_text(stmt, 2, [[NSString stringWithFormat:@"%@",[dict objectForKey:@"ProductName"]]UTF8String], -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, [[NSString stringWithFormat:@"%@",[dict objectForKey:@"ShortDescription"]]UTF8String], -1, SQLITE_STATIC);
if (sqlite3_step(stmt) != SQLITE_DONE)
{
printf("Commit Failed!\n");
}
sqlite3_reset(stmt);
}
if(sqlite3_exec(dtdb, "COMMIT TRANSACTION", NULL, NULL, &errorMessage)==SQLITE_OK)
{
NSLog(@"commited products all");
}
else
{
NSLog(@"commited fail products all");
}
sqlite3_finalize(stmt);
}
sqlite3_close(dtdb);