I've been searching around and not managed to find a solution or working example so here goes.
I've set up an SQLite database which has five columns with different fields which effectively builds a list for the user. There will be multiple values in the list that are the same, save for the ROWID which is set to auto increment.
Neither the user nor the program will know the ROWID once a value has been entered into the database, so I want for the user to be able to remove one row if it contains all four of the other fields.
My code looks like this:
Database
.delete(DATABASE_TABLE,
"KEY_DATE='date' AND KEY_GRADE='style2' AND KEY_STYLE='style' AND KEY_PUMPLEVEL='pumpLevel'",
null);
But this does not remove any values. I'm almost certain that the syntax of this command is to blame.
How do I format a where clause for delete command with multiple where clauses?
Solution from below:
ourDatabase.delete(DATABASE_TABLE, "ROWID = (SELECT Max(ROWID) FROM "
+ DATABASE_TABLE + " WHERE " + "date=? AND grade=? AND "
+ "style=? AND pump_level=?)", new String[] { date, grade,
style, pumpLevel });
I have a feeling that KEY_DATE
, KEY_GRADE
, etc are you Java variable names not your actual column names. Try changing your code to this:
.delete(DATABASE_TABLE,
KEY_DATE + "='date' AND " + KEY_GRADE + "='style2' AND " +
KEY_STYLE + "='style' AND " + KEY_PUMPLEVEL + "='pumpLevel'",
null);
Also I assume that 'date'
, 'style'
, etc are stored in local variables, you should use the whereArgs
parameter to project yourself from SQL Injection Attacks:
.delete(DATABASE_TABLE,
KEY_DATE + "=? AND " + KEY_GRADE + "=? AND " +
KEY_STYLE + "=? AND " + KEY_PUMPLEVEL + "=?",
new String[] {date, grade, style, pumpLevel});
(where date = "date"
, grade = "style2"
, etc)
Added from comments
To delete the last row use this:
.delete(DATABASE_TABLE,
"ROWID = (SELECT Max(ROWID) FROM " + DATABASE_TABLE + ")",
null);
To delete your last matching row try this:
.delete(DATABASE_TABLE,
"ROWID = (SELECT Max(ROWID) FROM " + DATABASE_TABLE + " WHERE " +
"KEY_DATE='date' AND KEY_GRADE='style2' AND " +
"KEY_STYLE='style' AND KEY_PUMPLEVEL='pumpLevel')",
null);
But see my second note about SQL Injection Attacks to protect your data.