我们如何打开一个已经存在的数据库fmdb以及在哪里包含它? [英] how do we open an already existing database fmdb and where to include it?

查看:257
本文介绍了我们如何打开一个已经存在的数据库fmdb以及在哪里包含它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fmdb,但我不知道在哪里添加db文件。
我发现这个旧答案,我认为它不适合xcode 4.2(因为我们没有'Resources'文件夹了。

I am using fmdb but i am not knowing where to add the db file. I found this old answer that i think it doesn't fit for xcode 4.2 (since we dont have 'Resources' folder anymore).

我在'Lita'中创建了一个数据库,添加了扩展名.sqlite并添加了db文件,如下所示:

I created a database in 'Lita', added the extension .sqlite and added the db file as follows :

然后尝试使用以下

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"db.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
FMResultSet *results = [database executeQuery:@"select * from tbl"];
printf("hi");
while([results next]) {
    printf("hi2");
NSString *name = [results stringForColumn:@"clm1"];
NSString *text  = [results stringForColumn:@"clm2"];        
NSLog(@"test: %@ - %@",name, text);
}
printf("done");

我得到'hi''完成'但从来没有'hi2'......

i am getting the 'hi' 'done' but never 'hi2'...

任何人都可以提供帮助吗?

anyone can help?

推荐答案

您想要添加(已编译)数据库以项目作为资源,然后在首次启动时将其复制到应用程序的文档文件夹中。

You want to add the (compiled) database to the project as a resource, and then copy it into the documents folder of the app on first start-up.

这是一个执行工作的示例方法,调用它来自applicationDidFinishLaunching并使用生成的FMDatabase *进行所有查询。

Here is an example method that does the work, call it from the applicationDidFinishLaunching and use the resultant FMDatabase * for all you queries.

- (FMDatabase *)openDatabase
{
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *documents_dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *db_path = [documents_dir stringByAppendingPathComponent:[NSString stringWithFormat:@"database.s3db"]];
    NSString *template_path = [[NSBundle mainBundle] pathForResource:@"template_db" ofType:@"s3db"];

    if (![fm fileExistsAtPath:db_path])
        [fm copyItemAtPath:template_path toPath:db_path error:nil];
    FMDatabase *db = [FMDatabase databaseWithPath:db_path];
    if (![db open])
        NSLog(@"Failed to open database!");
    return db;
}

这篇关于我们如何打开一个已经存在的数据库fmdb以及在哪里包含它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆