2

我尝试使用 SELECT DISTINCT sql 命令从数据库库中获取所有唯一值。但是当我的活动加载时出现异常,我在 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;
    }
4

3 回答 3

3

我认为您应该首先在此处此处查看这些答案,以查看 .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);

更新从这里 尝试答案。做这样的事情:

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

希望这有助于其他请评论。

于 2013-05-05T09:39:50.697 回答
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);

我希望它会有所帮助!

于 2013-05-05T10:08:18.843 回答
0

您错过了查询中的所有空格,您应该替换为:

String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;
于 2013-05-05T09:23:08.720 回答