ios - 如果 iOS sqlite 中不存在数据库,则导入

标签 ios sqlite

我的问题是它总是在渲染我的应用程序时从资源文件中导入 sqlite 数据库(它已经有很多设置数据)。我第一次呈现我的应用程序时,它从资源文件中导入 sqlite 数据库,然后我将一些数据插入到表中。但是第二次再次渲染,它再次导入并丢失了我插入的记录。以下是我的编码。

如果数据库存在,我想要的不需要导入。

static NaWinDatabase *_database;

+ (NaWinDatabase*)database {
    if (_database == nil) {
        _database = [[NaWinDatabase alloc] init];
    }
    return _database;
}

- (id)init {
    if ((self = [super init])) {
        NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:@"nawin" ofType:@"sqlite3"];

        if (sqlite3_open([sqLiteDb UTF8String], &_database) != SQLITE_OK) {
            NSLog(@"Failed to open database!");
        }
    }
    return self;
}

最佳答案

copyDatabaseIfNeeded 如果不是第一次复制,会将你的资源数据库复制到应用目录文件夹

+ (void) copyDatabaseIfNeeded {

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *dbPath = [self getDBPath];
    BOOL success = [fileManager fileExistsAtPath:dbPath];
    if(!success) {

        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sqlite"];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if (!success)
            NSAssert1(0, @"Failed to create writable database file with message \"%@\".", [error localizedDescription]);
    }
}

//你的数据库在应用程序文档目录中的保存路径

 + (NSString *) getDBPath {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *documentsDir = [paths objectAtIndex:0];
        return [documentsDir stringByAppendingPathComponent:@"db.sqlite"];
    }

关于ios - 如果 iOS sqlite 中不存在数据库,则导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23902497/

相关文章:

ios - 如何在自定义tableview单元类中使用UITableviewcell的dragStateDidChange方法

android - 维护一个 ListView,其中每个列表项都具有一对多关系

Android:为 MySQL 和 SQLite 数据库设计

sqlite - 无法解析调用者 sqlite3_bind : Do not understand this error in my Perl 6 script

objective-c - 应用程序终止时尝试保存到 plist

ios - UITextView 偏移文本的方式与 UILabel 不同

ios - 从 Open Street Map 下载一个国家的所有图 block

ios - 如何使用 libXML 在 xml 文件中获取编码?

SQLite 查询插入记录如果不存在

将 python 字典转换为 sqlite