我是一個新手,並在下面的代碼工作。作爲從CSV文件創建NSMutableDictionary的結果,我將值傳遞給DatabaseManager類,並且有一種方法接收這些值並嘗試將其插入數據庫。 1.如何將這些值插入到數據庫中? 2.是在iOS上製作小字典的有效方式嗎? (我有大約40000記錄,大小約3MB)iOS csv到sqlite
主類
... NSString *filePath= [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"csv"]; NSString *content = [[NSString alloc]initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; //NSString *path1=[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"JapMon" ofType:@"csv"] encoding:NSUTF8StringEncoding error:nil]; NSArray *messArr=[content componentsSeparatedByString:@"\n"]; if(messArr) { NSLog(@"%d", [messArr count]); for(int i=1;i<=[messArr count]-2;i++) { NSMutableDictionary *d=[[NSMutableDictionary alloc] init]; NSString *StrValue=[NSString stringWithFormat:@"%@",[messArr objectAtIndex:i]]; StrValue=[StrValue stringByReplacingOccurrencesOfString:@"\"" withString:@""]; StrValue=[StrValue stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // Here give whatever saperator you need to saperate data NSArray *arr=[StrValue componentsSeparatedByString:@","]; //NSLog(@"%@", [arr objectAtIndex:2]); [d setValue:[arr objectAtIndex:0] forKey:@"word"]; [d setValue:[arr objectAtIndex:1] forKey:@"hansa"]; [d setValue:[arr objectAtIndex:2] forKey:@"def"]; //Here add logic to insert row in your database table [[DatabaseManager getSharedInstance]insertInitialDataToDb:d]; //NSLog(@"%@", d); //Add this dictionary "d" into database [d release]; //Cleanup. } } //[content release]; ...
2.DATABASEMANAGER CLASS
-(BOOL) insertInitialDataToDb:(NSMutableDictionary*)initialData
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:@"insert into japmon (word, hansa, def) values (\"%@\")", initialData];
NSLog(@"ok");
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return TRUE;
}
else {
return FALSE;
}
sqlite3_reset(statement);
}
return TRUE;
我的數據庫使用全文搜索 – Johny
這是您需要定期執行的操作,還是僅在首次啓動時才執行一次?這些數據是否相當靜態,最好將CSV提前導入SQLite數據庫文件幷包含數據庫文件,而不是在代碼中完成所有這些操作。 – Devunwired
你爲什麼不使用核心數據? – HAS