ios - 从 bundle 中调用 sqlite 数据库

标签 ios iphone sqlite

我正在使用 sqlite 数据库,一切都很顺利。我在表中添加了 4 个条目,然后在我的 xib 文件中添加了 textview。现在我希望该数据应该从放置在项目包中的 sqlite 数据库中获取。但我不知道如何从 bundle 到目录路径调用该数据库。请帮我解决这个问题。

最佳答案

使用此代码:

首先调用此方法,该方法将检查 dbfile 是否存储在文档目录中。如果没有,它会将您的文件写入文档目录。

-(void)openDatabase {

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSString *dbPath = [self getDBPath];

    BOOL success = [fileManager fileExistsAtPath:dbPath];
    if(!success) {
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] 
                                   stringByAppendingPathComponent:@"databasefilename.sqlite"];

        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath
                                        error:&error];
        if (!success)
            NSLog(@"Failed to create writable database file with message '%@'.",
                      [error localizedDescription]);
    }
}

- (NSString *) getDBPath {
    //Search for standard documents using NSSearchPathForDirectoriesInDomains
    //First Param = Searching the documents directory
    //Second Param = Searching the Users directory and not the System
    //Expand any tildes and identify home directories.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,
                                                             NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    return [documentsDir stringByAppendingPathComponent:@"databasefilename.sqlite"];
}

然后 checkin Appdelegate 或您想要的任何其他类:

if (sqlite3_open([[self getDBPath] UTF8String], &YOUR_SQLITE3_OBJECT) == SQLITE_OK) {
    NSLog(@"database opened successfully");
}  

关于ios - 从 bundle 中调用 sqlite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218047/

相关文章:

ios - 使用 MusicSequenceFileCreate() 将 MusicSequence 保存到 .mid 文件

ios - 选项卡更改后导航栏下的表格 View

ios - 屏幕顶部边缘的自定义拖动 View 与通知中心冲突

php - sqlite 和窗口 : Not enough storage is available to complete this operation and CoInitialize has not been called

java - SQLite查询产生最后一个但一行值而不是最后插入的行值

php - 如何将数据从 iPhone 应用程序中的 SQLite 数据库发送到 Web 服务?

ios - Swift 3 类型转换期间的错误

ios - 在 GCDQueue 中创建和释放 NSMutableArray。这是正确的方法吗?

iphone - 更改父 View Controller 容器中的标签

iphone - 在当前时间 objective-c 上添加一毫秒