Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQLite - Using where args to delete by _id does NOT delete [duplicate]

Tags:

android

sqlite

Have this line of code in the getEvents method of my DBHelper.

    int year, month, day;
    String[] columns = new String[] { KEY_EVENTNAME, KEY_DESCRIPTION,
            KEY_HOUR, KEY_MINUTE, KEY_DAY, KEY_MONTH, KEY_YEAR,
            KEY_REMINDER };
    Cursor c = database.query(DATABASE_TABLE, columns, 
            KEY_YEAR + "=?"+ " AND " + KEY_MONTH + "=?" + " AND "+ KEY_DAY + "=?",
            new String[] {String.valueOf(year), String.valueOf(month), String.valueOf(day)}, 
            null, null, KEY_MONTH + " AND "
            + KEY_DAY);

It always returns nothing. When I remove the following

    int year, month, day;
    String[] columns = new String[] { KEY_EVENTNAME, KEY_DESCRIPTION,
            KEY_HOUR, KEY_MINUTE, KEY_DAY, KEY_MONTH, KEY_YEAR,
            KEY_REMINDER };
    Cursor c = database.query(DATABASE_TABLE, columns, 
            KEY_YEAR + "=?",
            new String[] {String.valueOf(year)}, 
            null, null, KEY_MONTH + " AND "
            + KEY_DAY);

it runs correctly. What's the problem with my code? It seems like it doesn't accept multiple values as where clause. Can any one help me with this? Thanks.

like image 942
TheGPWorx Avatar asked Jan 20 '26 16:01

TheGPWorx


1 Answers

The answer is in the title: you are trying to pass integer values into the query, but what you actually end up with are string values.

This is a horrible design bug in the Android database API; you can use parameters only for strings.

Integer numbers do not have the formatting and SQL injection problems that string values would have, so you can just insert the numbers directly into the SQL expression:

Cursor c = database.query(
    DATABASE_TABLE, columns, 
    KEY_YEAR  + "=" + year  + " AND " +
    KEY_MONTH + "=" + month + " AND " +
    KEY_DAY   + "=" + day,
    null, null, null,
    KEY_MONTH + "," + KEY_DAY);

(And the orderBy syntax was wrong.)

like image 91
CL. Avatar answered Jan 22 '26 22:01

CL.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!