4

In my app, I want to export a SQLite database file to CSV file..

Could you suggest me how to do this? Thanks.

Meghan
  • 1,004
  • 1
  • 15
  • 34

2 Answers2

15

First, you'll want to make sure that you're using FMDB to access the database, because people who use the SQLite C API directly in Objective-C are masochists. You can do that like this:

FMDatabase *db = [[FMDatabase alloc] initWithPath:@"/path/to/db/file"];
FMResultSet *results = [db executeQuery:@"SELECT * FROM tableName"];
while([results nextRow]) {
  NSDictionary *resultRow = [results resultDict];
  NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:@selector(compare:)];
  //iterate over the dictionary
}

As for writing to a CSV file, well there's code for that too:

#import "CHCSV.h"

CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:@"/path/to/csv/file" atomic:NO];

//write stuff
[csvWriter closeFile];
[csvWriter release];

And to combine them, you'd do:

FMDatabase *db = [[FMDatabase alloc] initWithPath:@"/path/to/db/file"];
if (![db open]) {
  //couldn't open the database
  [db release];
  return nil;
}
FMResultSet *results = [db executeQuery:@"SELECT * FROM tableName"];
CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initWithCSVFile:@"/path/to/csv/file" atomic:NO];
while([results nextRow]) {
  NSDictionary *resultRow = [results resultDict];
  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 closeFile];
[csvWriter release];

[db close];
[db release];

That will write the contents of the tableName table out to a CSV file.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • 1
    @Dave: Oh my god. I've never heard of FMDB. I am going to finally kill all of that native SQLite code in my app! Oh happy day!!!!! – Josh Jan 11 '11 at 17:00
  • 1
    @Josh you're welcome! There's a *ton* of open source stuff out there for Obj-C, so when in doubt, it's probably already been done for you (within reason) ;) I'd keep an eye on http://cocoaobjects.com – Dave DeLong Jan 11 '11 at 17:10
  • I am facing problems while importing my CSV file into my sqlite database. My csv file contains european languages with special character like umlaut. What could be wrong? – Meghan Jan 13 '11 at 11:03
  • @Meghan probably a file encoding issue. `CHCSVParser` attempts to figure out what encoding the csv file is, but it's by no means complete. The `NSArray` convenience methods have options to specify the file encoding of the file. Try those (I suggest `NSUTF8StringEncoding` as a first attempt), and send me an email if it doesn't work (contact info in my profile). – Dave DeLong Jan 13 '11 at 17:59
  • @Dave DeLong Thanks for your help. I have sent you the code where i am facing the problem on your website's contact. – Meghan Jan 17 '11 at 05:23
  • @Dave DeLong I have attached two csv files in reply of your mail. In console it shows me output of :NSLog(@"New : %@",myDBnew); (i.e. Path of my sqlite file) and then it crashes with error : *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array' – Meghan Jan 17 '11 at 07:07
  • @Dave DeLong can you please suggest me, I really need this urgently. – Meghan Jan 18 '11 at 03:48
  • @Dave DeLong I really appreciate your help, Thanks a lot. I sent you a mail about my console. – Meghan Jan 18 '11 at 04:21
  • @Dave DeLong I am preparing files and checking it now. I will definately let you know if anything happen. Thanks. – Meghan Jan 18 '11 at 04:58
  • Sorry to bump/necro this, but the code provided above contains code that are deprecated/changed in the current version of CHCSV. Can anyone provide an updated code? I am trying to achieve the exact same goal, exporting a whole sqlite database table to a csv file. – Razgriz Feb 26 '14 at 04:04
  • 1
    @Razgriz not much has different, and you can easily discern what you should be using by [reading the header file](https://github.com/davedelong/CHCSVParser/blob/master/CHCSVParser/CHCSVParser.h#L77). The initializer changes slightly (`initForWritingToCSVFile`), and `writeLine` and `closeFile` become `finishLine` and `closeStream`, respectively. – Dave DeLong Feb 26 '14 at 04:18
  • Then I remove the [csvWriter release] line, correct? ARC doesn't seem to allow it. – Razgriz Feb 26 '14 at 12:08
0

Simply do a SELECT on each table and print out the value of each column as required to a text file.

Andrew Ebling
  • 10,175
  • 10
  • 58
  • 75