如何在sqlite中使用FMDB以编程方式创建表



我是objective c的初学者,在我的项目中,我使用SQLite,这里我使用FMDB以编程方式创建表,但当运行项目时,它显示异常,如

"[NSFileManager copyItemAtPath:toPath:error:]:源路径为空"

请帮帮我。

这是我的代码

NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *dbUrl = [fileManager URLForDirectory:NSDocumentDirectory
                                       inDomain:NSUserDomainMask appropriateForURL:nil
                                         create:NO error:nil];
    dbUrl = [dbUrl URLByAppendingPathComponent:@"studentdb.sqlite"];
    FMDatabase * db = [FMDatabase databaseWithPath:dbUrl.absoluteString];
    if([db open]){
        NSString *dbCarTableCreate = @"CREATE TABLE IF NOT EXISTS studentInfo1(rollnum integer primary key autoincrement,name text,age text)";
        if([db executeUpdate:dbCarTableCreate]){
            NSLog(@"Table create success");
        }
        else{
            NSLog(@"%@",db.lastError);
            NSLog(@"%@",db.lastErrorMessage);
        }
    }

现在路径不是nil,如果您尝试下面的答案

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *documentsDirectory = [documentsDir stringByAppendingPathComponent:@"studentdb.sqlite"];
if (![[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory])
{
    NSString *backupDbPath = [[NSBundle mainBundle] pathForResource:@"studentdb" ofType:@"sqlite"];
    NSLog(@"Test backup path is - %@",backupDbPath);
    if (backupDbPath == nil)
    {
        NSLog(@"Database path is nil");
    }
    else
    {
        BOOL copiedBackupDb = [[NSFileManager defaultManager] copyItemAtPath:backupDbPath toPath:documentsDirectory error:nil];
        if (!copiedBackupDb){
            NSLog(@"Copying database failed");
        }
    }
}

输出

测试备份路径为"-"/用户/名称/图书馆/开发/CoreSimulator/设备/35 cdffa0 - 36 - a1 - 499 d - 8 d17 - 7 - ef356f1151e/数据/集装箱/包/应用程序/dea0343a - 05 - c8 - 4411 bf92 - 4000918 - e492a/DataBaseDemo.app studentdb.sqlite

最新更新