可能重复:
Exporting Sqlite table data to csv file programatically - xcode iOS 5 (for an ipad app)
我正在开发一个简单的应用程序。我正在使用sqlite将数据保存到表中(本地,在app documents文件夹中)。我想在csv文件中导出此表数据并将其通过电子邮件发送给某人。我的意思是我想在iPad转换后物理访问csv文件....任何人都可以提供示例应用程序下载吗?还是代码? 请帮忙
答案 0 :(得分:7)
这应该给你一个好主意。假设一个包含2行的表,此代码读取表中的所有值并将它们写入NSString
,然后将其写入文档目录中的CSV文件。如果您需要澄清如何使此代码适用于您的特定项目,请告诉我。
NSString *csv = [[NSString alloc] init];
sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *sqLiteDb
= [documentsDirectory stringByAppendingPathComponent:@"INSERT_DATABASE_NAME.sqlite3"];
if(sqlite3_open([sqLiteDb UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = [[NSString stringWithFormat:@"SELECT * FROM myTable"] UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
//this assumes that there are two rows in your database you want to get data from
[csv stringByAppendingFormat:@"%@,%@\n", [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)], [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]];
}
sqlite3_finalize(compiledStatement);
sqlite3_close(database);
}else{
NSLog(@"database error");
}
}
NSError *error = nil;
[csv writeToFile:[documentsDirectory stringByAppendingPathComponent:@"myFile.csv"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
[csv release];