Hi can I do this??,
int[] ids=new int[]{1,2,3,4,6,7,8,9,10};
db.execSQL(DELETE FROM TABLE_NAME WHERE id NOT IN ?,ids);
basically I want to delete all the rows that doesn't match my ids array.
So your problem is that you placed only one placeholder which will be replaced only with one value and array of args should have only one item. It should potentially work if you had 9x ? for each item in array.
It works as one placeholder - one value (same order). I wrote for you this snippet of code. Check it out.
int[] ids = new int[] {1,2,3,4,6,7,8,9,10};
StringBuilder query = new StringBuilder();
query.append("delete from table where column_id not in (");
for (int i = 0; i < ids.length; i++) {
query.append("?");
if (i < ids.length - 1) {
query.append(",");
}
}
query.append(")");
db.execSQL(query.toString(), ids);
Now it should works. Also ? character in dynamically created query is called placeholder and each placeholder will be replaced with value from String[] in same order.
I pretty recommend an usage of placeholders, whenever you will work with database. This approach is cleaner, safer and better looking.
public int delete() {
int[] ids = new int[] {1,2,3,4,6,7,8,9,10};
String[] args = new String[ids.length];
StringBuilder query = new StringBuilder();
query.append("delete from table where column_id not in (");
SQLiteStatement stmt = null;
for (int i = 0; i < ids.length; i++) {
args[i] = String.valueOf(ids[i]);
query.append("?");
if (i < ids.length - 1) {
query.append(",");
}
}
query.append(")");
stmt = db.compileStatement(query.toString());
stmt.bindAllArgsAsStrings(args);
return stmt.executeUpdateDelete();
}
executeUpdateDelete(); is only from API 11.You can use:
java.util.Arrays.toString(ids).replace('[', '(').replace(']', ')')
to convert the array to a suitable SQL where clause format
ids.toStringwill return object nametoString()on an array will return the instance name of the array. If you were to use anArrayListinstead you'd get [1,2,3,4,5...] returned. Anyways, using brackets in the SQL statement will fail.