Creating an SQLite3 database file through Objective-C

后端 未结 6 1630
攒了一身酷
攒了一身酷 2020-12-01 15:19

I\'m trying to create an SQLite3 database file through Objective-C at run time. I am trying to create a table called \"tblStore\". I want the field names to be called \"st

6条回答
  •  庸人自扰
    2020-12-01 15:51

    You can use following code to get the database created at in Documents folder. Just pass a path in documents folder and the function will copy the sqlite database in Documents folder at the given path if required. You can then use this path to create and query database tables.

    + (NSString*) createDatabaseIfRequiredAtPath:(NSString*)databasePath {
    
        if (databasePath == nil)
           return nil;
    
    
       NSString *path = [NSString stringWithFormat:@"%@/%@", databasePath, kMainDBName];
       NSFileManager *fileManager = [NSFileManager defaultManager];
       NSError *error = nil;
    
       if ([fileManager fileExistsAtPath:path] == NO) 
       {
        // The writable database does not exist, so copy the default to the appropriate location.
          NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:kMainDBName
                                                                  ofType:nil];
          BOOL success = [fileManager copyItemAtPath:defaultDBPath 
                                           toPath:path
                                            error:&error];
          if (!success)
          {
            NSCAssert1(0, @"Failed to create writable database file with message '%@'.", [  error localizedDescription]);
            return nil;
        }
    }
    
    return path;
    

提交回复
热议问题