在SQLite Android中订购数据

时间:2017-01-06 19:35:27

标签: android sqlite android-sqlite

我想通过COLUMN_NOMOR asc订购列表数据,但收到错误。

我有这样的代码

//  AMBIL SEMUA DATA 
    public List<Muridd> getSemuaMuridd() {
    List<Muridd> muriddList = new ArrayList<>();
    String selectQuery = "SELECT * FROM " + TABLE_MURIDD + "ORDER BY" + COLUMN_NOMOR + "ASC";
    SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

            if (cursor.moveToFirst()) {
                do {
                    Muridd muridd = new Muridd(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4),
                            cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8),
                            cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13));
                    muriddList.add(muridd);
                } while (cursor.moveToNext());
            }
                return muriddList;
        }

错误:

Caused by: android.database.sqlite.SQLiteException: no such table no such table: table_muriddORDER (code 1): , while compiling: SELECT * FROM table_muriddORDER BYnomorASC

当我尝试更改此行时

String selectQuery = "SELECT * FROM " + TABLE_CONTACT + "ORDER BY nomor ASC";

我也有错误:

Caused by: android.database.sqlite.SQLiteException: near "nomor": syntax error (code 1): , while compiling: SELECT * FROM table_muriddORDER BY nomor ASC

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

ORDER之前和BY

之后需要一个空格
String selectQuery = "SELECT * FROM " + TABLE_MURIDD + " ORDER BY " + COLUMN_NOMOR + " ASC";

防止此类事情的更好方法是使用String.format()例如

String selectQuery = String.format("SELECT * FROM %s ORDER BY %s ASC", TABLE_MURIDD, COLUMN_NOMOR);

请确保在下次发布到Stack Overflow之前检查简单的拼写错误,因为此类帖子为off-topic,即Questions about a problem that can no longer be reproduced or that was caused by a simple typographical error.

答案 1 :(得分:1)

连接SQL语句时出错:

String selectQuery = "SELECT * FROM " + TABLE_MURIDD + "ORDER BY" + COLUMN_NOMOR + "ASC";

应该是:

String selectQuery = "SELECT * FROM " + TABLE_MURIDD + " ORDER BY " + COLUMN_NOMOR + " ASC";

编辑:(感谢Michael Dogg

防止此类事情的更好方法是使用String.format(),例如。

String selectQuery = String.format("SELECT * FROM %s ORDER BY %s ASC", TABLE_MURIDD, COLUMN_NOMOR);

答案 2 :(得分:-1)

如果查看编译语句SELECT * FROM table_muriddORDER BY nomor ASC,您会发现表名和ORDER关键字之间缺少空格。

以下声明应修正错误。

String selectQuery = "SELECT * FROM " + TABLE_MURIDD + " ORDER BY " + COLUMN_NOMOR + " ASC";