objective-c - FMDB 使用字典查询

标签 objective-c ios5 sqlite fmdb

我需要运行一个看起来像这样的查询

INSERT INTO Appointments (field1, field2, field3, ..., field30) VALUES (value1, value2, value3, ..., value30)

我将我的约会存储在一个字典中,我想遍历该字典以使键等于字段并且值等于值。

我正在尝试使用 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];

        }

上面的代码打印了 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];

诀窍是将 ' 添加到数组中的数据。

关于objective-c - FMDB 使用字典查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9400087/

相关文章:

iphone - UIpageviewcontroller 首次加载 View 时仅在横向模式下加载单个 View

ios - Chartboost 委托(delegate)集成警告

objective-c - iOS 内存管理 - 说明

ios - UITextField文本在自定义单元格中重复

python - sqlite3.操作错误: unrecognized token: "01T00" Python datestamp

android - 如何将图库中的图像存储在 SQLite 数据库中

c# - 如何在 Xamarin iOS SQLite 中添加 SQLiteOpenFlags.FullMutex 标志

objective-c - API 失败,出现错误 Error Domain=NSURLErrorDomain Code=-1003

ios - UITableView 仅在第二次尝试时将数据发送到 Detail View Controller

html - 表单文本字段较多,需要解决方案