Question

So I'm trying to delete a Row from my database by passing the id of the specified row and I've found some code online but I really don't know how it works. It uses the whereClause argument in the db.delete method of SQLiteDatabase. Does anyone get the logic behind it? What getWhereClause does exactly?

 //the delete method in my database class
 public void deleteRow(String compareColumn, String compareValue) {
    // ask the database manager to delete the row of given id
    try {
        String whereClause = getWhereClause(compareColumn, compareValue);
    db.delete(TABLE_NAME, whereClause, null);
        //db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);
    } catch (Exception e) {
        Log.e("DB DELETE ERROR", e.toString());
        e.printStackTrace();
    }
}

  //the method that returns whereClause
private String getWhereClause(String compareColumn, String compareValue) {
    String whereClause = null;
    if (compareColumn == null || compareColumn == "") { }
    else if (compareValue == null || compareColumn == "") { }
    else { whereClause = compareColumn + "=\"" + compareValue + "\""; }
    return whereClause;
Was it helpful?

Solution

delete() uses the passed in whereClause to construct an SQL statement like DELETE FROM <tablename> WHERE <whereClause>. In case the passed in whereClause is null, the WHERE <whereClause> is omitted and all rows are deleted.

Your getWhereClause() constructs an expression that can be used as whereClause, comparing a column to a specified string literal value, like foo="bar". If either one is null or empty, a null whereClause is returned so all rows are matched.

OTHER TIPS

To simply explain, It takes two arguments

1.Column name

2.Column value

and creates a String literal and return it. Say for example 'student_id=100', where column name is student_id and column_value is 100. When any of the two arguments are null, then it returns null

It just checks that arguments are non-null/non-empty and returns the statement for the WHERE condition like the following: message = "Superman". So the result query will be like: DELETE FROM myTable WHERE message = "Superman"

BTW, since it's string literal, it's better to use single quotes instead of double quotes, like so whereClause = compareColumn + "='" + compareValue + "'"

The method deleteRow() gets the column (something like "Name") and the value (something like "Lukas"):

public void deleteRow(String compareColumn, String compareValue) 

The String variable whereClause uses the getWhereClause(column, value)- method to formate the both String variables in a SQL where clause like (WHERE name LIKE "Lukas").

Now the .delete() method of the Object db takes the variable whereClause as an argument and executes the delete query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top