简体   繁体   English

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

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

i am beginner in objective c in my project i am using SQLite and here i am creating table programmatically using FMDB but when ever run the project it's shows exception like 我是我的项目中目标c的初学者,我正在使用SQLite,在这里我正在使用FMDB以编程方式创建表,但是无论何时运行该项目,它都会显示异常

"[NSFileManager copyItemAtPath:toPath:error:]: source path is nil" “ [NSFileManager copyItemAtPath:toPath:error:]:源路径为空”

please help me some one 请帮我一个

This is my code 这是我的代码

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

Now the path is not nil,If you try the below answer 现在路径不为零,如果您尝试以下答案

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

The Output 输出

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