2011-01-11 39 views

回答

13

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

0

只需在每個表上執行SELECT並根據需要將每個列的值打印到文本文件中。