Adariel Lzinski
Adariel Lzinski

Reputation: 1121

Issue deleting row from database

So this seems pretty simple but I haven't been able to figure out what I'm doing wrong here. I have my database delete command:

public boolean deleteContact(String rowId) {
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

I also should mention that I am displaying the database in a listview. So when the user clicks on an item they are presented with a "OK" and a "Delete" option.

When they hit delete this is the command I'm using:

db.open();
db.deleteContact("Apple Recipe");
db.close();
dialog.dismiss();

I keep getting a force close issue that says:

android.database.sqlite.SQLiteException: ner "Recipe":syntax error
(code 1): , while compiling: DELETE FROM list WHERE item=Apple Recipe

I'm probably doing something stupid so maybe fresh eyes will help.

Upvotes: 0

Views: 69

Answers (3)

jbihan
jbihan

Reputation: 3099

Add ' in your delete statement, like this :

return db.delete(DATABASE_TABLE, KEY_ROWID + "='" + rowId + "'", null) > 0;

Or, as mentionned by other posters, you can use separate parameters :

String whereString = KEY_ROWID + "= ?";
String[] whereArgs = new String[] { rowId };
db.delete(DATABASE_TABLE, whereString, whereArgs);

Upvotes: 2

FabianCook
FabianCook

Reputation: 20557

To be honest you should be using:

return db.delete(DATABASE_TABLE, KEY_ROWID + "=?", new String[]{rowId}) > 0;

Its more of a safety thing to do with escaping the values to make sure no SQL is in the string that could execute

Upvotes: 1

nPn
nPn

Reputation: 16728

the delete method for a contentResolver takes, a Uri, a "where" string, and an args string. and row id is most likely an int

So it should be something like this db.delete(DATABASE_TABLE,"rowId = ? ", row_id_number);

or if you are looking to match some field such as "recipe" which is a string then. assuming the field name is recipe: db.delete(DATABASE_TABLE, "recipe = ?", "Apple Recipe");

Upvotes: 1

Related Questions