开发者

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

开发者 https://www.devze.com 2023-02-25 06:47 出处:网络
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 ins开发者_JS百科ert state

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 ins开发者_JS百科ert 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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号