我尝试使用SELECT DISTINCT sql命令从数据库coulmn获取所有唯一值。 但是当我的活动加载时我得到异常,我在logcat中有这个错误代码:
05-05 09:08:32.637: E/AndroidRuntime(1314): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workoutlog/com.example.workoutlog.AddWorkOutPage}: android.database.sqlite.SQLiteException: near "SELECT": syntax error (code 1): , while compiling: SELECT * FROM exerciseTable WHERE SELECT DISTINCTexercise_typefromexerciseTable
我认为我没有正确编写命令,这是我的代码:
public String[] getAllExercies() {
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
Cursor c = ourDatabase.query(TABLE_NAME, null, selecet, null, null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
String[] list = new String[c.getCount()-1];
int j = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
list[j] = c.getString(dayExercise);
j++;
}
return list;
}
答案 0 :(得分:2)
我认为您应首先查看这些答案here和here,以便查看.query()函数的工作情况。
请注意,使用ourDatabase.query()
函数时,参数如下:
String Table Name: The name of the table to run the query against
String [ ] columns: The projection of the query, i.e., the columns to retrieve
String WHERE clause: where clause, if none then pass null
String [ ] selection args: The parameters of the WHERE clause
String Group by: A string specifying group by clause
String Having: A string specifying HAVING clause
String Order By by: A string Order By by clause
所以你的第三个变量应该是 WHERE 子句,类似于:
String[] args = { "first string" };
Cursor c = ourDatabase.query("TABLE_NAME", null, "exercise_type=?", args, null, null, null);
由于您不需要WHERE子句,因此您可能希望使用rawQuery()方法。
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;
ourDatabase.rawQuery(selecet, null);
<强>更新强> 尝试here的答案。做这样的事情:
Cursor c = ourDatabase.query(true, "exerciseTable", new String[] {"exercise_type"}, null, null, "exercise_type", null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
//... continue with your further code
希望这有助于其他请评论。
答案 1 :(得分:1)
<强>问题:强>
你没有在单词之间保持space
。
<强>阐释:强>
假设,String COLUMN_EXERCISE = "exercise";
和String TABLE_NAME = "tbl_workout";
然后
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
只是意味着SELECT DISTINCTexercisefromtbl_workout
<强>解决方案:强>
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " from " + TABLE_NAME;
修改强>
请使用以下语法来激活rawQuery
Cursor c = ourDatabase.rawQuery(selecet,null);
我希望它会有所帮助!
答案 2 :(得分:0)
您错过了查询中的所有空格,您应该替换为:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;