Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Sqlite selection args[] with int values

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 687
TheGPWorx Avatar asked Dec 05 '22 09:12

TheGPWorx


2 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 52
CL. Avatar answered Jan 17 '23 19:01

CL.


I don't see anything wrong with the syntax or logic. Try checking if the values of year, month, and day are correct.

like image 39
josephus Avatar answered Jan 17 '23 19:01

josephus