Delete SQLite Row with where clause with multiple clauses

前端 未结 2 1949
余生分开走
余生分开走 2021-02-20 02:16

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 fie

相关标签:
2条回答
  • 2021-02-20 02:41

    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.

    0 讨论(0)
  • 2021-02-20 02:44

    You should use:

    Database.delete(DATABASE_TABLE,
                    "KEY_DATE=? AND KEY_GRADE = ? AND KEY_STYLE = ? AND KEY_PUMPLEVEL = ?",
                     new String[]{"date", "style2", "style", "pumpLevel"});
    

    which simplifies escaping values.

    0 讨论(0)
提交回复
热议问题