Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete row in database table given one column value - which is a string

Tags:

android

I have a table with column headings: | _id (long) | Name (String) | x (integer) | y (integer) |

I want to delete the row in the table that has Name myName.

// In onCreate
dbHelper = new DBAdapter(this);
dbHelper.open()

// Function in DBAdapter class
public boolean deleteTitleGivenName(String myName) 
{
    return dbHelper.delete(DATABASE_TABLE_2, KEY_NAME + "=" + myName, null) > 0;
}

// Function call in java code
dbHelper.deleteTitleGivenName(myName);  // this is where my code fails  

dbHelper.close();           

Just as a note: myName is for sure in the database. Also, I can not use the ROWID since I am getting myName from a ListView.

I just started programming with Android and I have tried for days to solve this problem. Is my WHERE clause correct (KEY_NAME + "=" + myName)?

Thanks in advance.

like image 448
Yasir Malang Avatar asked Jul 22 '10 22:07

Yasir Malang


People also ask

How do I delete a specific row value in SQL?

To remove one or more rows in a table: First, you specify the table name where you want to remove data in the DELETE FROM clause. Second, you put a condition in the WHERE clause to specify which rows to remove. If you omit the WHERE clause, the statement will remove all rows in the table.


2 Answers

Sure, that works, although I would recommend

dbHelper.delete(DATABASE_TABLE_2, KEY_NAME + "=?", new String[] { myName })

for safety reasons. That way, you can have special characters without breaking your query. Did this not work?

like image 59
EboMike Avatar answered Sep 20 '22 18:09

EboMike


Try putting the value of the where clause in quotes...

KEY_NAME + "='" + myName + "'"

Also, it is bad practice (generally) to use a string-based WHERE clause. This is because if my name has an apostrophe in it, your app will not work. You should probably look for an alternative way to delete records from a database on Android.

like image 34
dacris Avatar answered Sep 21 '22 18:09

dacris