IOS~FMDB数据库管理的那些坑-入门级

IOS本地持久化有4种:属性列表、对象归档、SQLite3和Core Data;

其中属性列表和SQlite3是本人强烈推荐的。对象归档较为繁琐,coreData没有用过暂不评价。

1.属性列表简单说一下:最普遍用的最广泛的持久化方法;

  • 1).分开存取
    // 存
    [[NSUserDefaults standardUserDefaults] setInteger:userID forKey:@”userID”];
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:@”name”];
    // 取
    NSInteger uId = [[[NSUserDefaults standardUserDefaults] integerValueForKey:@”userID”];
    NSString * name = [[NSUserDefaults standardUserDefaults] stringForKey:@”name”];
  • 2).按对象存取
    // 存
    [[NSUserDefaults standardUserDefaults] setObject:self forKey:@”user”];
    // 取
    User * u = [[NSUserDefaults standardUserDefaults] [objectForKey”@”user];

2.好了进入今天的正题~数据库Sqlite3

  • 说到SQlite3嵌入式数据库不得不提一个强大的第三方FMDB
    有FMDB,OC与SQlite的交互变得不那么困难,化繁为简。

  • 但是很多小伙伴对sqlite语法很陌生,导致FMDB无缘无故的坑自己。
    下面我就来简单分享自己对FMDB的理解以及IOS数据库本地持久化的万能常用语句。

  • 最开始我们建一个单例类来创建和管理数据库。
    如下:
    @implementation DataBaseManagerShoppingCar
    {
    //数据库管理对象
    FMDatabase *_fmdb;
    }
    -(instancetype)init{
    //1.抛异常
    @throw [NSException exceptionWithName:@”DataBaseManagerShoppingCar” reason:@”不能调用初始化方法” userInfo:nil];
    return self;
    //2.断言,判定言论,程序崩溃
    // NSAssert(false, @”DataBaseManager无法调用该方 法”);
    }
    //重新实现初始化方法
    -(instancetype)initWithPrivate
    {
    if (self =[super init]) {
    [self createDataBase];
    }
    return self;
    }

     +(instancetype)sharedManager
    {
     static DataBaseManagerShoppingCar *manager =nil;
     static dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
        if (!manager) {
          manager =[[DataBaseManagerShoppingCar    alloc]initWithPrivate];
          }
       });
       return manager;
        //    //2.
        //    @synchronized(self){
        //        if (!manager) {
         //            manager =[[self alloc]initPrivate];
        //        }
       //    }
      }
       //初始化数据库
       -(void)createDataBase
       {
        //获取沙箱路径下的Documents
         NSArray *documentsPath =    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
       NSString *dbPath =[[documentsPath fir   stObject]stringByAppendingPathComponent:@"ShoppingCar.db"];
         NSLog(@"%@",dbPath);
         if (!_fmdb) {
          //创建数据库管理对象
           _fmdb =[[FMDatabase alloc]initWithPath:dbPath];
          }
         //打开数据库
          if ([_fmdb open]) {
          //创建数据库表
             [_fmdb executeUpdate:@"create table if not exists ShoppingCar (productId integer, productName str, thumb str,type integer,num integer,unitPrice double,farmId integer,deliveryWeekIndex integer,payType integer);"];
            }
          }
    
增删查
  • 判断APPID对应的数据是否存在
    -(BOOL)isExistsProductId:(NSInteger)productId
    {
    FMResultSet * rs =[_fmdb executeQuery:@”select *from ShoppingCar where productId =?”,@(productId)];
    // 判断结果集是否存在
    // if ([rs next]) {
    // return YES;
    // }
    // else{
    // return NO;
    // }
    return [rs next];
    }

  • 添加数据
    -(BOOL)insertProductId:(NSInteger)productId ProductName:(NSString )productName Thumb:(NSString *)thumb Type:(NSInteger)type Num:(NSInteger)num UnitPrice:(double)unitPrice FarmId:(NSInteger)farmId DeliveryWeekIndex:(NSInteger)deliveryWeekIndex PayType:(NSInteger)payType
    {
    //判断AppId在数据库中是否存在
    //这里要特别提出来说一下,问号代表的是对象,如果你存的常量请先转成对象存进去。比如@(Float) 还有
    if(![self isExistsProductId:productId]){
    //如果不存在
    BOOL success =[_fmdb executeUpdate:@”insert into ShoppingCar values(?,?,?,?,?,?,?,?,?)”,@(productId),productName,thumb,@(type),@(num),@(unitPrice),@(farmId),@(deliveryWeekIndex),@(payType)];
    return success;
    }
    return YES;
    }
    -(BOOL)removeAllobjects
    {
    BOOL succese = [_fmdb executeUpdate:@”delete from ShoppingCar”];
    return succese;
    }
    -(BOOL)removeProductId:(NSInteger)productId
    {
    BOOL succese =[_fmdb executeUpdate:@”delete from ShoppingCar where productId=?”,@(productId)];
    return succese;
    }
    -(managerModel *)selectCurrentModelWithProductId: (NSInteger)productId
    {
    FMResultSet *rs =[_fmdb executeQuery:@”select *from ShoppingCar where productId =?”,@(productId)];
    managerModel *model =[[managerModel alloc]init];
    while([rs next]){
    model.productId =[rs intForColumn:@”productId”];
    model.productName =[rs stringForColumn:@”productName”];
    model.thumb =[rs stringForColumn:@”thumb”];
    model.type =[rs intForColumn:@”type”];
    model.num =[rs intForColumn:@”num”];
    model.unitPrice =[rs doubleForColumn:@”unitPrice”];
    model.farmId =[rs intForColumn:@”farmId”];
    model.deliveryWeekIndex =[rs intForColumn:@”deliveryWeekIndex”];
    model.payType =[rs intForColumn:@”payType”];
    }
    return model;
    }

     -(NSArray *)selectAllApps
     {
     //从表中获取所有数据
      FMResultSet *rs =[_fmdb executeQuery:@"select *from ShoppingCar"];
     //遍历结果集
      NSMutableArray *apps =[NSMutableArray array];
      while([rs next]){
      managerModel *model =[[managerModel alloc]init];
      model.productId =[rs intForColumn:@"productId"];
      model.productName =[rs stringForColumn:@"productName"];
      model.thumb =[rs stringForColumn:@"thumb"];
      model.type =[rs intForColumn:@"type"];
      model.num =[rs intForColumn:@"num"];
      model.unitPrice =[rs doubleForColumn:@"unitPrice"];
      model.farmId =[rs intForColumn:@"farmId"];
      model.deliveryWeekIndex =[rs intForColumn:@"deliveryWeekIndex"];
      model.payType =[rs intForColumn:@"payType"];
      [apps addObject:model];
      }
       return [apps copy];
       }
      //修改数据
     -(BOOL)updateProductId:(NSInteger)productId Num: (NSInteger)num
     {
        BOOL succese =[_fmdb executeUpdate:@" update   ShoppingCar set num =? where productId=?",@(num),@(productId)];
             return succese;
      }
    
  • FMDB的三种查询方法
    -(FMResultSet )executeQuery:(NSString)sql, …
    – (FMResultSet )executeQueryWithFormat:(NSString)format, …
    – (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments
    // executeUpdate : 不确定的参数用?来占位
    [self.db executeUpdate:@”INSERT INTO t_student (name, age) VALUES (?, ?);”, name, @(arc4random_uniform(40))];
    //也可以这样表示
    //NSString *tableName =@”t_student (name, age)”;
    //[self.db executeUpdate:[NSString stringWithFormat:@”insert into %@ VALUES(?,?)” ,tableName],name, @(arc4random_uniform(40))];
    [self.db executeUpdate:@”INSERT INTO t_student (name, age) VALUES (?, ?);” withArgumentsInArray:@[name, @(arc4random_uniform(40))]];
    // executeUpdateWithFormat : 不确定的参数用%@、%d等来占位
    //此处一定要注意Format后面不是单纯的字符串NSString,不能随便的组装字符串,它只能接Values括号里面的占位参数,不能更改Values前面的参数,例如:
    错误的表达:
    [self.db executeUpdateWithFormat:@”INSERT INTO %@ VALUES (%@, %d);”, @”t_student (name, age)”,name, arc4random_uniform(40)];
    正确表达:
    [self.db executeUpdateWithFormat:@”INSERT INTO t_student (name, age) VALUES (%@, %d);”, name, arc4random_uniform(40)];

FMDB的坑几乎就搞定了,小伙伴如有什么问题或者本文有不妥,欢迎致电QQ309685725

    原文作者:yeshenlong520
    原文地址: https://www.jianshu.com/p/99f2ecd4cd1b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞