【问题标题】:Adding NULL Values to SQLite Database with FMDB and NSDictionary使用 FMDB 和 NSDictionary 向 SQLite 数据库添加 NULL 值
【发布时间】:2013-08-13 20:19:04
【问题描述】:

我遇到了一些问题 22。我正在使用 FMDB 的花哨withParameterDictionary 方法将数据插入到我的 SQLite 数据库中,如下所示:

NSDictionary *aircraftDict = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.aircraftIdTextField.text, @"aircraft_id",
                              self.makeModelTextField.text, @"make_model",
                              self.categoryClassTextField.text, @"category_class",                                  
                              @YES, @"updated_flag",                                 
                              nil];

NSString *addAircraftQuery = @"INSERT INTO aircrafts (aircraft_id, make_model, category_class, updated_flag) VALUES (:aircraft_id, :make_model, :category_class, :updated_flag)";

[db executeUpdate:addAircraftQuery withParameterDictionary:aircraftDict];

问题在于,当其中一个文本字段为空白时,它会截断 NSDictionary,因为 nil 值告诉字典它已到达其值列表的末尾。

我可以通过确保字典中的每个值都有一个空白对象(例如字符串@"")来解决这个问题。

然后我的值作为“空白”值而不是NULL 到达我的 SQLite 数据库。这可能没什么大不了,但我听说使用NULL 会占用更少的数据库空间。

如何在不提前截断我的 NSDictionary 的情况下将NULL 插入我的数据库?

【问题讨论】:

    标签: ios sqlite fmdb


    【解决方案1】:

    也花了一些时间研究这个。我的解决方案(使用 Swift,但 Objective C 应该相同)是使用 NSNull 而不是 nil

    【讨论】:

      【解决方案2】:

      你可以不使用“花哨”的 withParameterDictionary 方法,而是使用枯燥的 executeUpdate 方法,如下所示:

      NSString *addAircraftQuery = @"INSERT INTO aircrafts (aircraft_id, make_model, category_class, updated_flag) VALUES (?, ?, ?, ?)";
      
      [db executeUpdate:addAircraftQuery, self.aircraftDict, self.makeModelTextField.text, self.categoryClassTextField.text, @YES];
      

      【讨论】:

      • 也许我会考虑在我原本诱人的代码中添加一些这种平凡的东西。 ;) 感谢您的帮助。
      • 谢谢你也帮助了我
      【解决方案3】:

      为了保持美观,试一试,对我有用:

      NSDMutableDictionary *aircraftDict = [NSDMutableDictionary dictionary];
      // only insert non-nil text fields
      if(self.aircraftIdTextField.text){
          aircraftDict[@"aircraft_id"] = self.aircraftIdTextField.text;
      }
      etc for all other text fields...
      
      NSArray* keys = [aircraftDict allKeys];
      NSMutableArray *prefixedKeys = [NSMutableArray array];
                  [keys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                      [prefixedKeys addObject:[NSString stringWithFormat:@":%@",obj]];
                  }];
      NSString *addAircraftQuery = [NSString stringWithFormat: @"INSERT INTO aircrafts (%@) VALUES (%@)",[keys componentsJoinedByString:@","],[prefixedKeys componentsJoinedByString:@","]];
      [db executeUpdate:addAircraftQuery withParameterDictionary:aircraftDict];
      

      现在插入只包含您要插入的字段,因此非常高效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-17
        • 2015-01-02
        • 1970-01-01
        • 2018-03-13
        • 2023-04-03
        • 1970-01-01
        相关资源
        最近更新 更多