如何将NSDictionary中的数据写入SQLite数据库?

时间:2011-10-10 09:51:46

标签: iphone sqlite nsdictionary sbjson

  

可能重复:
  separating keys and objects from NSMutable dictionary and use the values in insert command of sqlite

我有一个包含已解析的JSON数据的NSDictionary。如何将这些数据推送到数据库,以便我可以从数据库中提取它们以供进一步使用?

我正在使用SBJSON进行解析。

3 个答案:

答案 0 :(得分:2)

如果您的设计要求指定sqlite,那么我建议使用Gus Mueller的FMDB,这样您就不必直接使用原始sqlite。

NSString $title = [jsonDictionary objectForKey:@"title"];
//  other keys, values, etc...
NSString $query = [NSString stringWithFormat:@"INSERT INTO myTable t (t.some_column) VALUES ('%@'),$title];
FMResultSet *results = [_db executeQuery:$query];

如上所述,正如克里斯所说,核心数据通常是比sqlite更好的解决方案。 Brent Simmons(NetNewsWire开发人员)有一系列有关此主题的帖子,如this one.

对于我来说,“核心数据比sqlite更好”的例外情况是你想要提供初始数据但不想执行初始导入核心数据的情况。

答案 1 :(得分:0)

使用核心数据来解决这个问题。这是一个很好的教程: http://mobile.tutsplus.com/tutorials/iphone/iphone-core-data/

答案 2 :(得分:0)

以下代码创建动态plist文件,该文件存储到bundle中,可以访问该数据并将数据插入.plist文件。

NSString *strPathToAudioCache=[NSString stringWithFormat:@"%@/%@",
                                           [(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],
                                           @"data.plist"];


            NSMutableDictionary *dOfAudios=[NSMutableDictionary dictionaryWithContentsOfFile:strPathToAudioCache];
            NSLog([dOfAudios allKeys].count>0?@"Value is exist":@"Value is not exist");
            if([dOfAudios allKeys].count>0) {
                [dOfAudios setValue:@"Key_for_value" forKey:@"value_for_key"];
            } else {

                dOfAudios=[NSMutableDictionary dictionary];
                [dOfAudios setValue:@"Key_for_value" forKey:@"value_for_key"];

            }
            [dOfAudios writeToFile:strPathToAudioCache atomically:YES];
相关问题