Question

I have searched through all the questions, but did not find an answer yet. The closest I came to was this Passing an array to sqlite WHERE IN clause via FMDB? . However, the answer suggested did not seem to work. The command does not throw any error, however it does not perform the intended operation (e.g. DELETE) either. Here's what I am trying to do :

[myDB executeUpdateWithFormat:@"DELETE FROM table WHERE row_id IN (%@)",rowIdsToBeDeleted];

rowIdsToBeDeleted is a comma seperated NSString containing rowIds as NSNumber objects, e.g.

1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012

I even tried using the executeUpdate, but no luck. Could any of you please help ?

Était-ce utile?

La solution

If that method is anything like the NSPredicate syntax, simply remove the parenthesis (they are handled for you (and pass in a collection instead of a string):

NSArray *ids = [rowIdsToBeDeleted componentsSeparatedByString:@","];
[myDB executeUpdateWithFormat:@"DELETE FROM table WHERE row_id IN %@",ids];

edit

Also, usually you pass in an actual collection object (not a string)... above edited to reflect

Autres conseils

You could do simply:

[myDB executeUpdate:[NSString stringWithFormat:@"DELETE FROM table WHERE row_id IN (%@)",rowIdsToBeDeleted]];

Despite what one might otherwise infer from the method name, the executeUpdateWithFormat method does not perform traditional printf-style formatting. Behind the scenes, what it really does is iterate through the format strings, replacing the printf-style strings with ? placeholders, and then try to the appropriate sqlite3_bind_xxx function to bind the values to those placeholders.

This implementation of executeUpdateWithFormat introduces all sorts of subtle issues. (Because of this, it is likely to be deprecated in future FMDB versions.) In this particular case, the problem is that sqlite3_bind_xxx can not bind a comma separated string as an array of values to be bound to a single ? placeholder.

Generally one should avoid using stringWithFormat (or Swift string interpolation) to build SQL statements to be passed to FMDB or SQLite because if done improperly, you can be exposed to SQL injection attacks and/or fail if you fail to properly escape string values. But this example, where you want to test to see if some numeric value is within a set of numeric values, is an exception to that rule and you can use stringWithFormat as shown above.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top