Android Sqlite selection args[] with int values

后端 未结 3 1367
执念已碎
执念已碎 2020-11-29 11:02

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

    int year, month, day;
    String[] columns = new String[] { KEY_EVENTNAME, KEY_DESCRIPTION         


        
相关标签:
3条回答
  • 2020-11-29 11:18

    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.)

    0 讨论(0)
  • 2020-11-29 11:24

    Thank you for all your help. After considering everything you suggested, I have finally found out the cause why it always returns nothing. The month value that I passed to this method was incorrect. It was a month ahead that's why it returns 0 for the current month. I'm sorry for the trouble. But all your answers are correct. It was a fault that I believe most or some have experienced. As a learning, I'd give extra care in looking into the values that I pass. Carefully looking into the flow of the values that are passed between methods saves time. I spent the whole night looking for the problem and just this morning after waking up I remembered the value that was passed into the method. Thanks again to everyone who gave the answers.

    0 讨论(0)
  • 2020-11-29 11:37

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

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