如何为NSDictionary进行键/值配对

时间:2014-12-26 13:52:36

标签: json sorting ios6 nsdictionary

我的词典输出是 - 我想触发insert命令将此字典数据插入到sqlite数据库

(
    {
    iCardReceiverName = rp;
    iCardSenderName = madhusudan;
    isDeleted = 0;
    isReceiverSynk = 0;

},
    {
    iCardReceiverName = rp;
    iCardSenderName = mmmm;
    isDeleted = 0;
    isReceiverSynk = 0;

}

我想将这些数据插入到sqlite数据库中。

这是我的代码 -

                           NSDictionary *jsonData = [NSJSONSerialization
                                                      JSONObjectWithData:urlData
                                                     options:NSJSONReadingMutableContainers
                                                      error:&error];


            NSMutableString *query = [NSMutableString stringWithFormat:@"Insert into iCardUsers ("];
            [self.dbManager executeQuery:query];
            if (self.dbManager.affectedRows != 0) {
                NSLog(@"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows);
            }
            else{
                NSLog(@"Could not execute the query.");
            }


            for (int i = 0; i<[[jsonData allKeys] count]; i++)
            {
                [query appendFormat:@"%@,",[[jsonData allKeys] objectAtIndex:i]];
            }
            [query appendFormat:@")values ("];
            for (int i = 0; i<[[jsonData allKeys] count]; i++)
            {
                [query appendFormat:@"%@,",[jsonData valueForKey:[[jsonData allKeys] objectAtIndex:i]]];
            }

            [query appendFormat:@");"];
            NSLog(@"qry : %@",query);

1 个答案:

答案 0 :(得分:0)

您可以在sqlite db中插入数据,如下例所示。 您可以使用所需参数创建一个函数,并使用该函数插入数据。

-(void)InsertRecords:(NSMutableString *)txt{

    NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"movieData.sqlite"];
    const char *dbpath = [dbPath UTF8String];
    sqlite3 *contactDB;

    sqlite3_stmt    *statement;

    NSLog(@"%@",dbPath);
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO myMovies (movieName) VALUES (\"%@\")", txt];

        const char *insert_stmt = [insertSQL UTF8String];

        sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            sqlite3_bind_text(statement, 1, [txt UTF8String], -1, SQLITE_TRANSIENT);
        } else {
            NSLog(@"error");
        }
        sqlite3_finalize(statement);
        sqlite3_close(contactDB);
    }
}