Bot*_*Bot 3 sqlite objective-c fmdb ios5
我需要运行看起来像的查询
INSERT INTO Appointments (field1, field2, field3, ..., field30) VALUES (value1, value2, value3, ..., value30)
Run Code Online (Sandbox Code Playgroud)
我将我的约会存储在一个字典中,并希望循环该字典以使键等于字段,值等于值.
executeUpdate:... withParameterDictionary:...如果我不知道字段名称,我正在尝试使用但无法弄清楚如何使用多个字段.字段名称是通过JSON发送的,而不是手动输入30个字段,我只想循环遍历字典并以这种方式获取它们.
我甚至试过了
NSMutableArray *keys = nil;
NSMutableArray *values = nil;
for (NSDictionary *dict in [json objectForKey:@"data"]) {
keys = [NSMutableArray array];
values = [NSMutableArray array];
for (id key in dict) {
[keys addObject:key];
[values addObject:[NSString stringWithFormat:@":%@", key]];
}
NSString *keyString = [keys componentsJoinedByString:@","];
NSString *valueString = [values componentsJoinedByString:@","];
[[dataObj db] executeUpdate:@"DELETE FROM Appointments"];
NSLog(@"INSERT INTO Appointments (%@) VALUES (%@)", keyString, valueString);
[[dataObj db] executeUpdate:@"INSERT INTO Appointments (?) VALUES (?)", keyString, valueString];
}
Run Code Online (Sandbox Code Playgroud)
上面的代码打印NSLog查询应该如何显示,但没有任何内容插入到数据库中.我知道这是因为我在查询运行后打开模拟器数据库文件并且它仍然是空白的.
如何使上述代码工作或如何executeQuery:... withParameterDictionary:...使用多个名称.
我跑了几个快速测试,这对我有用:
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:@"AAAA44", @"a", @"BBBB44", @"b", @"CCCC44", @"c", nil];
NSMutableArray* cols = [[NSMutableArray alloc] init];
NSMutableArray* vals = [[NSMutableArray alloc] init];
for (id key in dict) {
[cols addObject:key];
[vals addObject:[dict objectForKey:key]];
}
NSMutableArray* newCols = [[NSMutableArray alloc] init];
NSMutableArray* newVals = [[NSMutableArray alloc] init];
for (int i = 0; i<[cols count]; i++) {
[newCols addObject:[NSString stringWithFormat:@"'%@'", [cols objectAtIndex:i]]];
[newVals addObject:[NSString stringWithFormat:@"'%@'", [vals objectAtIndex:i]]];
}
NSString* sql = [NSString stringWithFormat:@"insert into test (%@) values (%@)", [newCols componentsJoinedByString:@", "], [newVals componentsJoinedByString:@", "]];
NSLog(@"%@", sql);
BOOL updateSuccess = [db executeUpdate:sql];
Run Code Online (Sandbox Code Playgroud)
诀窍是添加'到数组中的数据.