ios数据库

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值