Skip to content

Instantly share code, notes, and snippets.

@AlexHedley
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save AlexHedley/4ac103b5018c9d5fa974 to your computer and use it in GitHub Desktop.

Select an option

Save AlexHedley/4ac103b5018c9d5fa974 to your computer and use it in GitHub Desktop.
Export SQLite to CSV
FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
[db open];
FMResultSet *results = [db executeQuery:@"SELECT * FROM tblScores"];
//CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initForWritingToCSVFile:[NSHomeDirectory() stringByAppendingPathComponent:@"demo.csv"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *document = [[NSString alloc] initWithFormat:@"%@/demo.csv", documentsDirectory];
CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initForWritingToCSVFile:document];
while([results next]) {
//NSDictionary *resultRow = [results resultDict];
NSDictionary *resultRow = [results resultDictionary];
NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:@selector(compare:)];
//iterate over the dictionary
for (NSString *columnName in orderedKeys) {
id value = [resultRow objectForKey:columnName];
[csvWriter writeField:value];
}
//[csvWriter writeLine];
[csvWriter finishLine];
}
//[csvWriter closeFile];
[csvWriter closeStream];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment