我正在嘗試構建我作爲iPhone開發人員的技能,目前我正在使用SQLite數據庫。我創建了一個SQLite表在我GroceryListAppDelegate.m類如下:無法檢索和查看SQLite數據庫的結果
- (void)applicationDidFinishLaunching:(UIApplication *)application {
self.database = [[[ISDatabase alloc] initWithFileName:@"TestDB.sqlite"] autorelease];
if(![[database tableNames] containsObject:@"GroceryItem"]) {
[database executeSql:@"create table GroceryItem(primaryKey integer primary key autoincrement, name text NOT NULL, number integer NOT NULL)"];
[database executeSql:@"insert into GroceryItem (name, number) values ('apples', 5)"];
[database executeSql:@"insert into GroceryItem (name, number) values ('oranges', 3)"];
}
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
}
我對我做RootViewController.m類SQL調用:
- (void)viewDidLoad {
[super viewDidLoad];
GroceryList1AppDelegate *appDelegate = (GroceryList1AppDelegate *)[[UIApplication sharedApplication] delegate];
self.results = [appDelegate.database executeSqlWithParameters:@"SELECT * from GroceryItem where number < ?", [NSNumber numberWithInt:6], nil];
}
我executeSqlWithParameters()方法是這樣的:
- (NSArray *) executeSql:(NSString *)sql withParameters: (NSArray *) parameters {
NSMutableDictionary *queryInfo = [NSMutableDictionary dictionary];
[queryInfo setObject:sql forKey:@"sql"];
if (parameters == nil) {
parameters = [NSArray array];
}
//we now add the parameters to queryInfo
[queryInfo setObject:parameters forKey:@"parameters"];
NSMutableArray *rows = [NSMutableArray array];
//log the parameters
if (logging) {
NSLog(@"SQL: %@ \n parameters: %@", sql, parameters);
}
sqlite3_stmt *statement = nil;
if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
[self bindArguments: parameters toStatement: statement queryInfo: queryInfo];
BOOL needsToFetchColumnTypesAndNames = YES;
NSArray *columnTypes = nil;
NSArray *columnNames = nil;
while (sqlite3_step(statement) == SQLITE_ROW) {
if (needsToFetchColumnTypesAndNames) {
columnTypes = [self columnTypesForStatement:statement];
columnNames = [self columnNamesForStatement:statement];
needsToFetchColumnTypesAndNames = NO;
}
id row = [[NSMutableDictionary alloc] init];
[self copyValuesFromStatement:statement toRow:row queryInfo:queryInfo columnTypes:columnTypes columnNames:columnNames];
[rows addObject:row];
[row release];
}
}
else {
sqlite3_finalize(statement);
[self raiseSqliteException:[[NSString stringWithFormat:@"failed to execute statement: '%@', parameters: '%@' with message: ", sql, parameters] stringByAppendingString:@"%S"]];
}
sqlite3_finalize(statement);
return rows;
}
當我構建和運行我的代碼,我沒有得到任何結果,而事實上,給我的SQL調用,我應該得到蘋果,橘子和我的列表中。然而,當我修改我的SQL代碼如下:
self.results = [appDelegate.database executeSql:@"SELECT * from GroceryItem"];
它調用不同的方法:的ExecuteSQL():
- (NSArray *) executeSql: (NSString *)sql {
return [self executeSql:sql withParameters: nil];
}
在這種情況下,我最終得到的結果:蘋果,橙子。爲什麼是這樣?我究竟做錯了什麼?爲什麼我從一個SQL調用中獲取結果,而不是從另一個調用中獲得結果?
非常感謝您的回覆。但是,我將如何從模擬器中提取.sqlite文件,並使用sqlite3在命令行上打開它?再次感謝你的幫助。 – syedfa 2010-12-02 03:34:42