SQL Android Query formulation with multiple conditions
I am writing an android application that is trying to pull data from a database based on two separate criteria.
The fields of workout and exercise are both strings in the database. I want to return a cursor with only those rows that satisfy BOTH criteria. Oh and I would also like it to be sorted in date order...
public Cursor graphQuery(String exercise, String work开发者_如何学Goout) {
Cursor cursor = mDb.query(DATABASE_TABLE, new String [] {KEY_DATE, KEY_REPS,
KEY_REPS_FEEL, KEY_WEIGHT, KEY_WEIGHT_FEEL}, "KEY_WORKOUT=" + workout + "AND" +
"KEY_EXERCISE=" + exercise, null , null, null, KEY_DATE);
return cursor;
}
I am a new android coder and would appreciate the help!
Use selection
and selectionArgs
:
public Cursor graphQuery(String exercise, String workout) {
Cursor cursor = mDb.query(DATABASE_TABLE, new String [] {KEY_DATE, KEY_REPS,
KEY_REPS_FEEL, KEY_WEIGHT, KEY_WEIGHT_FEEL}, "KEY_WORKOUT = ? AND KEY_EXERCISE = ?",
new String[] { workout, exercise },
null,
null,
KEY_DATE);
return cursor;
}
Notice how the selection
String
has ?
s inplace of actual values and the actual values are passed in as a String[]
and in the selectionArgs
paramter. SQLite will replace those ?
s with the values from the String[]
selectionArgs
.
Short answer: There are spaces missing around "AND" --> " AND ".:
Long answer: Please use parameter markers - you will see missing spaces immediately then:
Cursor cursor = mDb.query(DATABASE_TABLE, new String [] { KEY_DATE, KEY_REPS,
KEY_REPS_FEEL, KEY_WEIGHT, KEY_WEIGHT_FEEL }, "KEY_WORKOUT=? and KEY_EXERCISE=?", new String[] { workout, exercise }, null, null, KEY_DATE);
精彩评论