尝试打开(创建)SQLite d / b时出错(“EXC_BAD_ACCESS”)

时间:2011-04-26 20:33:42

标签: objective-c sqlite

这是代码......有人看到了什么问题吗?另外,为什么“errmsg”的第二个NSLog会在调试到设备时导致调试器崩溃(iPhone 3GS)

    // Get the path to the database file
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [searchPaths objectAtIndex:0];
NSString *databasePath = [documentPath stringByAppendingPathComponent:@"ppcipher.s3db"];
const char *cDatabasePath = [databasePath cStringUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"databasePath: %@", databasePath);

    NSString *sqlCommand = @"CREATE TABLE CardData (card_id TEXT PRIMARY KEY NOT NULL, card_name TEXT NOT NULL, "
        @"card_type TEXT, cide_val TEXT, create_date TEXT DEFAULT CURRENT_DATE, user_notes TEXT, gps_loc TEXT)"; 
    const char cSQLCommand = [sqlCommand cStringUsingEncoding:NSUTF8StringEncoding];
    char * errmsg = NULL;   

    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:databasePath error:NULL];  //  <------------  delete d/b  TESTING ONLY! 

    BOOL fileExists = [fileManager fileExistsAtPath:databasePath];
    if(!fileExists)  {
        if(sqlite3_open(cDatabasePath, db) == SQLITE_OK) { // doesn't exist, so create it...
            sqlite3_exec(db, &cSQLCommand, NULL, NULL, &errmsg);  //  now create the table...
            NSLog(@"error: %@", errmsg);
        }

1 个答案:

答案 0 :(得分:2)

崩溃是因为errmsg不是Objective-C对象,您需要使用%@替换。 errmsgchar *,这意味着您应该使用%s

至于它崩溃的原因......

sqlite3_open定义为:

int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);

您的db被声明为sqlite3*。换句话说,你传递了错误的东西。你应该这样做:

sqlite3_open(cDatabasePath, &db)

虽然您希望了解SQLite C API,但我仍然认为您应该使用FMDB。它确实减轻了这些错误,让您专注于代码中的实际问题。