朋友只是一般问题。如何将sqlite数据写入并检索到文件
如何将数据写入并检索到该文件。以及如何使该文件在.csv格式中。
例如我是检索类似
NSString *coords = [[[NSString alloc] initWithFormat:@"%f,%f\n",longitude,latitude] autorelease];
[locations addObject:coords];
比.csv格式怎么能写上文件这个数据。
而且比我怎样才能检索数据
朋友只是一般问题。如何将sqlite数据写入并检索到文件
如何将数据写入并检索到该文件。以及如何使该文件在.csv格式中。
例如我是检索类似
NSString *coords = [[[NSString alloc] initWithFormat:@"%f,%f\n",longitude,latitude] autorelease];
[locations addObject:coords];
比.csv格式怎么能写上文件这个数据。
而且比我怎样才能检索数据
要撰写CSV
NSString *coords = [[[NSString alloc] initWithFormat:@"%f,%f\n",longitude,latitude] autorelease];
NSData *csvData = [coords dataUsingEncoding:NSUTF8StringEncoding];
NSArray *UsrDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocsDir = [UsrDocPath objectAtIndex:0];
NSString *csvPath = [DocsDir stringByAppendingPathComponent:@"coords.csv"];
//This is upto your logic that do you want to remove existant csv file or not
BOOL success = [FileManager fileExistsAtPath:csvPath];
if(success){
[FileManager removeItemAtPath:csvPath error:&error];
}
[csvData writeToFile:csvPath atomically:YES];
从文件中读取
NSData *csvData = [NSData dataWithContentsOfFile:csvPath];
NSString *strCSV = [[NSString alloc]initWithData:csvData encoding:NSUTF8StringEncoding];
希望它可以帮助
首先,您需要确保您使用的是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];
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];
需要写入表名表的内容进行到CSV文件。
然后,您可以使用CSV解析器解析CSV并获取数据。
我很困惑。可以更好地解释请 – Shima
Shima,上面的代码是用于从数据库获取数据,然后写它进入文件.CSV。写完后,如果想要从CSV读取数据,则需要使用CSV解析器。 –
有使用CSV格式的特定需要,你可以将其转换成SQLite数据库,然后你可以在sqlite上工作... – iMOBDEV
没有具体的使用.csv合成。我只是想写入数据文件,其中有csv fromat。并检索到 – Shima
我有一个已答复,您是否想从/到/ csv文件进行读取/写入? – iMOBDEV