2012-12-06 156 views

回答

0

执行以下步骤来导入CSV到sqlite3的数据库

  1. 将文件添加到您的资源文件夹。(假设文件的名称是“List.csv”)

  2. 先弄CSV文件的路径。

    NSString *path = [[NSBundle mainBundle] pathForResource:@"List" ofType:@"csv"]; 
    
  3. 编写下面的方法来解析并插入到数据库中。

    [self insertIntoDatabaseFromFile:path]; 
    
  4. 的方法去如下

    -(void)insertIntoDatabaseFromFile:(NSString*)path 
    { 
    
    NSString *fileDataString=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 
    
    //Gives u the array with all lines separated by new line. 
    NSArray *linesArray=[fileDataString componentsSeparatedByString:@"\r"]; 
    int k = 0; 
    for (id string in linesArray){ 
    
        //Gives u the number of items in one line separated by comma(,) 
        NSString *lineString=[linesArray objectAtIndex:k]; 
    
        //Gives u the array of all components. 
        NSArray *columnArray=[lineString componentsSeparatedByString:@","]; 
    
        //Get elements from array and create a query to add all into database. 
        //Write your code for that. 
    
        k++; 
    
    }