将csv文件导入SQLite

时间:2012-09-25 10:12:08

标签: iphone objective-c sqlite csv import

我在SQLite中有一个数据库,还有一个名为 xyz 的表是空的。我想将csv文件中的数据导入到该表中。

现在,当我尝试导入csv文件时,它要求我将其导入主表,但我想将数据导入我的 xyz 表。

我该怎么做?

3 个答案:

答案 0 :(得分:3)

我完成了下面的代码,你只需要表达: -

 -(void)restore{
 @try {
      NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@%@?userid=%@",kHOSTPATH,kCSVLIST,[[cntrAppDelegate setServerDetails] valueForKey:@"kUSERID"]]];
 NSMutableURLRequest *requestMutable = [[NSMutableURLRequest alloc] init];
 [requestMutable setURL:url];
 NSError *error = [[NSError alloc] init];
 NSHTTPURLResponse *response = nil;
 NSData *urlData=[NSURLConnection sendSynchronousRequest:requestMutable returningResponse:&response error:&error];
 NSLog(@"Response code: %d", [response statusCode]);
 if ([response statusCode] >=200 && [response statusCode] <300)
 {
  NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
  NSLog(@"Response ==> %@", responseData);
  SBJsonParser *jsonParser = [SBJsonParser new];
  NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
  NSLog(@"--------=========%@============-------------",jsonData);
  NSDictionary *dic = [jsonData objectForKey:@"Root"];
  NSLog(@"---------------------ROOT VALUE IS %@",dic);
  NSLog(@"----------------COUNT IS %d",[dic count]);
  for (int i = 0; i < [dic count]; i++) 
  {
       NSString *str = [[dic valueForKey:@"CSV_File"]objectAtIndex:i];
       NSLog(@"STR IS %@",str);
        [self.arrListOfCSV addObject:str];
   }
   if ([jsonData valueForKey:@"Root"] == 0)
   {

   }
    else
   {
   }
   } 

答案 1 :(得分:3)

你可以这样做,

首先,您需要在捆绑包中添加csv文件。

然后,您可以在此处使用csv

在数据库中添加数据的方法
-(void)loadCSVData{
NSString *path1=[[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"YOUR_CSV_FILENAME" ofType:@"csv"]  usedEncoding:&encoding error:nil];
NSArray *messArr=[path1 componentsSeparatedByString:@"\n"];
if(messArr)
{
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:@","];

 [d setValue:[arr objectAtIndex:0] forKey:@"YOUR_TABLE_FIELD_1"];
 [d setValue:[arr objectAtIndex:1] forKey:@"YOUR_TABLE_FIELD_2"];
 [d setValue:[arr objectAtIndex:2] forKey:@"YOUR_TABLE_FIELD_3"];

  //Here add logic to insert row in your database table
}
}

答案 2 :(得分:0)

您最好在Linux中导入数据。在进入SQLite后的磁盘操作系统中,输入

separator",";

进口choose your csv path的xyz。当您创建名为xyz的表时,该名称应与您的csv文件一致。