在我的应用中,我想将一个SQLite数据库文件导出为CSV文件。你能建议我如何做吗?谢谢。
首先,你需要确保在访问数据库时使用的是FMDB,因为直接在Objective-C中使用SQLite C API的人们是一群受虐狂。你可以这样做:
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文件,这里也有相关的代码:点击此处
#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文件中。
initForWritingToCSVFile
),writeLine
和closeFile
分别变成了finishLine
和closeStream
。 - Dave DeLong