【问题标题】:How to export SQLite file into CSV file in iPhone SDK如何在 iPhone SDK 中将 SQLite 文件导出为 CSV 文件
【发布时间】:2011-06-07 02:42:12
【问题描述】:

在我的应用程序中,我想将 SQLite 数据库文件导出为 CSV 文件..

你能建议我怎么做吗? 谢谢。

【问题讨论】:

  • 数据库有一张还是多张表?

标签: iphone objective-c csv sqlite export-to-excel


【解决方案1】:

首先,您需要确保使用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 文件,好吧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 文件。

【讨论】:

  • @Dave:天哪。我从来没有听说过FMDB。我将最终杀死我的应用程序中的所有原生 SQLite 代码!哦,快乐的一天!!!!
  • @Josh,不客气! Obj-C 有 的开源东西,所以如果有疑问,它可能已经为你完成了(在合理的范围内);)我会密切关注 cocoaobjects.com
  • 我在将 CSV 文件导入我的 sqlite 数据库时遇到问题。我的 csv 文件包含具有特殊字符(如变音符号)的欧洲语言。有什么问题?
  • @Meghan 可能是文件编码问题。 CHCSVParser 试图弄清楚 csv 文件的编码是什么,但这绝不是完整的。 NSArray 便捷方法具有指定文件的文件编码的选项。试试这些(我建议NSUTF8StringEncoding 作为第一次尝试),如果它不起作用,请给我发送电子邮件(我的个人资料中的联系信息)。
  • @Razgriz 没什么不同,reading the header file 可以很容易地辨别出你应该使用什么。初始化器略有变化(initForWritingToCSVFile),writeLinecloseFile 分别变为 finishLinecloseStream
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2014-02-22
    • 2018-07-23
    • 2023-03-23
    • 2011-04-16
    • 2015-09-30
    相关资源
    最近更新 更多