Tutorial :SQLITE Selection and order by causing errors



Question:

i'm trying to get a query that returns rows only with a specified name, and sort descending by week (integer).

Everytime I try and run it it gives me a FC and logcat says

ERROR/AndroidRuntime(728): android.database.sqlite.SQLiteException: no such column: New: , while compiling: SELECT Name, Week, Total FROM notes WHERE Name=New ORDER BY WeekDESC LIMIT 10

    public Cursor graphQuery(String name){      return mDb.query(DATABASE_TABLE, new String[] {KEY_NAME,              KEY_WEEK, KEY_TOTAL}, KEY_NAME + "=" + name, null, null, null, KEY_WEEK + "DESC","10");  }  

It says that there is no such column, which doesn't make sense because it should be looking at the names in the row and returning the ones that match. Also if I put KEY_NAME + "=" + name as null, it says that there is no such column WeekDESC which doesn't make sense either cause it is just supposed to be sorting by an integer.

I have gotten this code working before, but I misplaced it and can't seem to get it working again... This is getting frustrating, any help is very much appreciated!


Solution:1

If you search by string, you should use a question mark as a placeholder, i.e.

return mDb.query(DATABASE_TABLE, new String[] {KEY_NAME,              KEY_WEEK, KEY_TOTAL}, KEY_NAME + "=?", new String[] { name }, null, null, null, KEY_WEEK + "DESC","10");  

Or else it will break if the name contains spaces or special characters. (If you really don't want to you the question mark, you need to put the string in quotes or double-quotes, but using a question mark is far more elegant and safe.)

Also: There is no space between "DESC" and the key you're sorting by. Use " DESC".


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »