SQL读取数据?

时间:2010-11-13 19:25:24

标签: iphone sql objective-c sqlite

我使用下面的代码从file.sql读取数据没有任何问题是否有问题?

+ (void) getInitialDataToDisplay:(NSString *)dbPath {

SQLAppDelegate *appDelegate = (SQLAppDelegate *)[[UIApplication sharedApplication] delegate];

if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

    const char *sql = "select coffeeID, coffeeName from coffee";
    sqlite3_stmt *selectstmt;
    if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {

        while(sqlite3_step(selectstmt) == SQLITE_ROW) {

            NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
            Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
            coffeeObj.CoffeeName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];

            coffeeObj.isDirty = NO;

            [appDelegate.coffeeArray addObject:coffeeObj];
            [coffeeObj release];
        }
    }
}
    else
        sqlite3_close(database);
}

appDelegate.m      - (void)applicationDidFinishLaunching:(UIApplication *)application {

[self copyDatabaseIfNeeded];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
self.coffeeArray = tempArray;
[tempArray release];

[Coffee getInitialDataToDisplay:[self getDBPath]];
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];

}

1 个答案:

答案 0 :(得分:0)

执行是否会进入while子句?

除了已经提出的建议外,还有以下几点需要尝试:

1)在模拟器上启动您的应用程序。使用SQLite数据库浏览器(http://sqlitebrowser.sourceforge.net)打开数据库文件并验证该表是否存在。检查表名和列名的确切拼写。

2)检查数据库是否正在打开文件,并且dbPath是应用程序沙箱中数据库文件的正确路径。应使用NSDocumentsDirectory生成路径:

 NSArray*  paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];

3)确保使用sqlite_finalize正确清理所有旧语句并正确关闭数据库。 sqlite_close不应该在“else”子句中。