2

I have a list containing some 'product' objects and want to delete all the products row in the DB that are not in that list based on their unique attribute serialNumber.

Example, if my list contain:

  • product A
  • product B
  • product C

My DB contain:

  • product A
  • product B
  • product C
  • product D

Then I want to remove product D from the DB.

This is my list:

List<Product> products;

I'm thinking of looping on the list to create a string array serialNumbers of serialNumber.

String[] serialNumbers;

for (int i=0; i<products.size(); i++){
    //Insert serialNumbers in Array
}

and then something like:

database.delete(MySQLiteHelper.TABLE_PRODUCTS, MySQLiteHelper.COLUMN_SERIALNUMBER + " NOT IN " + SerialNumbers, null);

How could I do the database query?

1 Answer 1

5

You can build the inQuery like this:

StringBuilder inQuery = new StringBuilder();

inQuery.append("(");
boolean first = true;
for (String item : serialNumbers) {
    if (first) {
        first = false;
        inQuery.append("'").append(item).append("'");
    } else {
        inQuery.append(", '").append(item).append("'");
    }
}
inQuery.append(")");

then use it:

database.delete(MySQLiteHelper.TABLE_PRODUCTS, MySQLiteHelper.COLUMN_SERIALNUMBER + " NOT IN " + inQuery.toString(), null);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.