繁体   English   中英

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

[英]How to create table programmatically in sqlite using FMDB

我是我的项目中目标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);
        }
    }

现在路径不为零,如果您尝试以下答案

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");
        }
    }
}

输出

测试备份路径为-/Users/name/Library/Developer/CoreSimulator/Devices/35CDFFA0-36A1-499D-8D17-7EF356F1151E/data/Containers/Bundle/Application/DEA0343A-05C8-4411-BF92-4000918E492A/DataBaseDemo.app/ studentdb.sqlite

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM