简体   繁体   中英

How to export SQLite file into CSV file in iPhone SDK

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

Could you suggest me how to do this? Thanks.

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.

只需在每个表上执行SELECT,并根据需要将每列的值打印到文本文件中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM