在我的应用中,我想将SQLite数据库文件导出为CSV文件..
你能建议我怎么做吗? 感谢。
答案 0 :(得分:15)
首先,您需要确保使用FMDB来访问数据库,因为直接在Objective-C中使用SQLite C API的人是masochists。你可以这样做:
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
}
至于写入CSV文件,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];
要结合它们,你可以做到:
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];
这会将tableName
表的内容写入CSV文件。
答案 1 :(得分:0)
只需在每个表上执行SELECT,并根据需要将每列的值打印到文本文件中。