separating keys and objects from NSMutable dictionary and use the values in insert command of sqlite

僤鯓⒐⒋嵵緔 提交于 2019-12-19 10:56:23

问题


hi folks i am developing an sqlite application in iphone. since i am new to this application, i dont how to use the key and objects from NSMutableDictionary in the command of insert statement of sqlite. for example , i want the insert statement in the following format.

INSERT INTO TABLENAME (COLUMN NAMES AS KEYS FROM NSMUTABLEDICTIONRY) VALUES (VALUES AS OBJECTS FROM NSMUTABLEDICTIONARY) please help me out. thanks


回答1:


I have actually very little knowledge about SQL, but maybe something like this will help you:

NSDictionary *myDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"Foo", @"Bar",
                              @"Foz", @"Baz",
                              nil];

NSMutableString *keys = [NSMutableString string];
NSMutableString *values = [NSMutableString string];
for (NSString *key in myDictionary) {
    [keys appendFormat:@"%@,", key];
    [values appendFormat:@"%@,", [myDictionary objectForKey:key]];
}
// remove last ,
[keys deleteCharactersInRange:NSMakeRange([keys length]-1, 1)];
[values deleteCharactersInRange:NSMakeRange([values length]-1, 1)]; 
NSString *sqlQuery = [NSString stringWithFormat:@"INSERT INTO TABLENAME %@ VALUES %@", keys, values];

// sqlQuery = INSERT INTO TABLENAME Bar,Baz VALUES Foo,Foz



回答2:


NSArray *keys = [dictionary allKeys];
NSMutableArray *values = [NSMutableArray array];
for (id k in keys)
    [values addObject:[dictionary objectForKey:k]];



回答3:


You can use fast enumeration to loop through the dictionary:

NSDictionary *abc;
for (NSString *key in abc) {
     NSObject *foo = [abc objectForKey:key];
}

With that it should be easy to construct your statement.



来源:https://stackoverflow.com/questions/5677396/separating-keys-and-objects-from-nsmutable-dictionary-and-use-the-values-in-inse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!