Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

objective c - How to delete Multiple row from one table in sqlite iOS?

I have a table, MessageTable in sqlite.I want to delete selected rows from it. How can I achieve that. I have searched hard but didn't get any suitable answer. Any help would be appreciated. TIA.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to delete the multiple selected rows from a table, IN clause will be the one of the best choice. While deleting the rows you need to take care what kind of column you are going to mention in the condition.

Here are the various data types mentioned how to delete the set of rows from a table.

For Numbers:

NSString *query = [NSString stringWithFormat:@"DELETE FROM Messages WHERE ID IN (101,102,103,104)];;

Here for Numbers or Integers, we can set the Array of Numbers directly to the query or we can set as comma separated values.

Accommodating array in the Query.

NSArray *idArraysToDelete = @[101, 102, 103, 104];
NSString *query = [NSString stringWithFormat:@"DELETE FROM Messages WHERE (ID IN %@)", idArraysToDelete];

For Strings:

Lets say you want to delete the messages of few selected peoples,

NSMutableArray *parameters = [NSMutableArray new];
for (id avatar in avatarNames) {
    if (avatar != [NSNull null]) {
        if ([avatar isKindOfClass:[NSString class]]) {
            NSString *strValue = [NSString stringWithFormat:@"'%@'", avatar];
            [parameters addObject:strValue];
        } else {
            [parameters addObject:bindVal];
        }
    }
}
NSString *deleteQuery = [NSString stringWithFormat:@"DELETE FROM Messages WHERE AVATAR IN (%@)", tableName, columnName, [parameters componentsJoinedByString:@","]];

Here for Strings, SQLite always assumes the VARCHAR or String may contain UNICode characters, So while setting the parameters we are setting single quote('') for each values. SQLite will assume the value mentioned in the single quotes are the row values. In general for any condition check on strings, single quotes are mandatory


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...