2

我有 JSON 格式的数据,我正在尝试生成 SQL 插入语句,以便可以将数据加载到 SQLite 数据库的表中。

我的 JSON 看起来像这样:

{
    "data": [
        {
            "cities": [
                "Washington",
                "Washington"
            ],
            "num_buildings": 2,
            "building_ids": [
                "604159",
                "634589"
            ]
        },
        {
            "cities": [
                "Buffalo",
                "Buffalo",
                "Boston"
            ],
            "building_count": 3,
            "building_ids": [
                "652100",
                "676349",
                "652101"
            ]
        }
    ]
}

我解析 JSON 并得到如下数据结构。

{
cities =         (
    Washington,
    Washington
);
"num_buildings" = 2;
"event_ids" =         (
    604159,
    634589
  );
},
{
cities =         (
     Buffalo,
     Buffalo,
     Boston
);
"num_buildings" = 3;
"building_ids" =         (
     652100,
     676349,
     652101
  );
}

接下来我想生成 SQL 语句,以便将数据加载到表中。

NSDictionary *JSONDictionary = [self JSONDictionaryForClassWithName:@"myJSON"];
NSArray *records = [JSONDictionary objectForKey:@"data"];
  for (NSDictionary *record in records) {
  [self mergeRecordsForClassName:className forRecord:record] ;
};
NSLog(@"Initial sync recs are %@",records);
-(void)mergeRecordsForClassName:(NSString *)entityName forRecord:(NSDictionary *)record {
  NSString *insert_stmt2 =[NSString stringWithFormat:@"INSERT OR REPLACE INTO %@("
    "city,building_count,building_id") values("
    "'%@',%i,'%@') ",
    entityName,
    [record valueForKey:@"cities"],
    [[record valueForKey:@"building_count"]  intValue],
    [record valueForKey:@"building_id"]
    ];
    NSLog(@"The insert stmt2 is %@",insert_stmt2);
}

它生成如下 SQL 语句,这显然是错误的。

INSERT OR REPLACE INTO building(building_id,building_count,city) 
values('
  ("604159",
    "634589"
   )',
   3,
'(Washington,
  Washington'
)
)

如何每行生成一个 SQL 语句,如下所示:

INSERT OR REPLACE INTO building(building_id,building_count,city) values('604159',3,;Washington');
INSERT OR REPLACE INTO building(building_id,building_count,city) values('634589',3,;Washington'); 

等等

谢谢 !

4

0 回答 0