将sqlite DB导出为csv - Sqlite.swift

时间:2015-07-12 15:10:58

标签: ios database sqlite csv sqlite.swift

我在iOS应用程序中使用sqlite。我想导出这个数据库并将其放在一个集中的数据库中。如何导出sqlite db?我正在使用sqlite.swift。谢谢!

1 个答案:

答案 0 :(得分:0)

以下仅是代码的一部分。粘贴在下面是回答你的问题所需要的:

- (NSString *)dataFilePathCustom:(NSString *)filename withExtension:(NSString *)ext {
    NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dictionaryDocuments = [paths objectAtIndex: 0];
    return [dictionaryDocuments stringByAppendingPathComponent: [NSString stringWithFormat: @"%@.%@", filename, ext]];

}

- (void)SQL_ITEMS_voidExportCSVFormat {
    NSString *string = @"\"CSV Export\"";
    NSArray *arrayContents = [self SQL_returnContentsOfTable];
    for (NSArray *arrayItem in arrayContents) {
        string = [string stringByAppendingFormat: @"\r%d,\"%@\",%d", [arrayItem[0] intValue], arrayItem[1], [arrayItem[2] intValue]];

    }

    [string writeToFile: [self dataFilePathCustom: @"ExportFile" withExtension: @"csv"] atomically: YES encoding: NSUTF8StringEncoding error: nil];

}

- (void)viewDidLoad {
    [self SQL_voidClearRowsFromTable];
    [self SQL_ITEMS_voidInsertRowWithArray: @[@"ONE", @25]];
    [self SQL_ITEMS_voidInsertRowWithArray: @[@"TWO", @225]];
    [self SQL_ITEMS_voidInsertRowWithArray: @[@"THREE", @21]];
    [self SQL_ITEMS_voidInsertRowWithArray: @[@"FOUR", @55]];
    [self SQL_ITEMS_voidInsertRowWithArray: @[@"FIVE", @56]];
    [self SQL_ITEMS_voidInsertRowWithArray: @[@"SIX", @77]];
    [self SQL_ITEMS_voidInsertRowWithArray: @[@"SEVEN", @25]];
    [self SQL_ITEMS_voidExportCSVFormat];


}

example

这行代码NSArray *arrayContents = [self SQL_returnContentsOfTable];返回SQL表的内容。 SELECT * FROM Items;是用于填充此数组的查询arrayContents