ios数据库

来源:互联网 发布:男朋友礼物学生知乎 编辑:程序博客网 时间:2024/05/16 12:10

DataBase.h文件

#import <sqlite3.h>//导入系统的文件

@interface DataBase : NSObject
//该类用于操作数据库,该类只提供了两个方法
//1.openDataBase,
//2.closeDataBase,
//如果我们想要使用数据库,需要添加SQLite3.0.dylib库,然后导入sqlite3.头文件
//SQLite3.0.dylib是一个快捷方式,永远指向的时最新的sqlite库
+ (sqlite3 *)openDataBase;
+ (void)closeDataBase;

DataBase.m文件

@implementation DataBase
static sqlite3 *sqlite =nil;
+ (sqlite3 *)openDataBase
{
    if (sqlite) {
        return sqlite;//保证每次使用数据库时只打开一次.如果sqlite为空,说明第一次打开数据库,然后执行下面的代码,打开数据库,当下一次再调用该方法时,直接将sqlite返回就可以了,(之前数据库已经打开)
    }
    //如果我们想要对数据库文件进行更改,我们必须要将该数据库文件从包中拷贝到Documents文件夹下,包中的内容是不可被修改的.
    //获取Documents文件夹的路径

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    //获取Documents/DB.sqlite路径.
    NSString *newFilePath = [documentPath stringByAppendingPathComponent:@"DB.sqlite"];
    NSLog(@"%@",newFilePath);
    //判断该文件是否存在,如果不存在,就将包中的DB.sqlite拷贝到Documents文件夹下.
    //NSFileManager 是一个文件管理类,能够对沙盒中的文件进行增删改操作.

    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断该文件是否存在
   BOOL isExist = [fileManager fileExistsAtPath:newFilePath];
    if (!isExist) {
        //获得包中文件路径
        NSString *bundlePath = [[NSBundle mainBundle]pathForResource:@"DB.sqlite" ofType:nil];
        //将数据库文件拷贝到Document/DB.sqlite路径下.
     BOOL isSuccess = [fileManager copyItemAtPath:bundlePath toPath:newFilePath error:nil];
        NSLog(@"%d",isSuccess);
        
    }
    //通过指定路径来打开数据库,这时sqlite就指向了打开的数据库
    sqlite3_open([newFilePath UTF8String], &sqlite);
    return sqlite;
   

}
+ (void)closeDataBase
{
    if (sqlite) {//已经打开过,就关闭.
        sqlite3_close(sqlite);
    }
}


0 0
原创粉丝点击