从Sqlite检索数据时出错

时间:2015-03-12 04:12:58

标签: android

我想从数据库中检索数据,而且餐馆ID应按升序排序,我尝试使用查询检索数据。有人请帮助我,我真的找不到什么错误

    Cursor cursor = db.rawQuery("SELECT  " + key_id_cart + " as _id,  "
            +" ORDER BY "+ restaurant_ID +  " DESC"+", " + restaurant_name + ", "
            + restaurant_thumbnail + ", " + dishname + ", " + dish_image
            + ", " + AreaId + ", " + ItemChoiceIds + ", " + ItemChoiceQty
            + ", " + ItemId + ", " + Quantity + " from "
            + tablenameCartData, new String[] {});

问题是它返回如下的异常

   android.database.sqlite.SQLiteException: near "ORDER": syntax error (code 1): , while compiling: SELECT  key_id_cart as _id,   ORDER BY restaurant_ID DESC, restaurant_name, restaurant_thumbnail, dishname, dish_image, AreaId, ItemChoiceIds, ItemChoiceQty, ItemId, Quantity from tablenameCartData

4 个答案:

答案 0 :(得分:3)

将您的查询更改为以下内容 由于Order by

之前的, order byCursor cursor = db.rawQuery("SELECT " + key_id_cart + " as _id," + restaurant_name + ", " + restaurant_ID + "as res_id," + restaurant_thumbnail + ", " + dishname + ", " + dish_image + ", " + AreaId + ", " + ItemChoiceIds + ", " + ItemChoiceQty + ", " + ItemId + ", " + Quantity + " from " + tablenameCartData + " ORDER BY res_id DESC", new String[] {}); 应始终在查询结束时发出错误
{{1}}

答案 1 :(得分:2)

ORDER BY名称之后添加tablenameCartData或在选择查询的末尾添加:{/ p>

Cursor cursor = db.rawQuery("SELECT  " + key_id_cart + " as _id,  "
            + restaurant_ID +  " "+", " + restaurant_name + ", "
            + restaurant_thumbnail + ", " + dishname + ", " + dish_image
            + ", " + AreaId + ", " + ItemChoiceIds + ", " + ItemChoiceQty
            + ", " + ItemId + ", " + Quantity + " from "
            + tablenameCartData+" ORDER BY <COLUMN_NAME> DESC", new String[] {});

其中COLUMN_NAME是想要订购查询响应的列名称

答案 2 :(得分:1)

SQL查询中的语法错误:

正确的语法是:

  

SELECT column-list

     

FROM table_name

     

[WHERE条件]

     

[ORDER BY column1,column2,.. columnN] [ASC | DESC];

代码应该是: Cursor cursor = db.rawQuery("SELECT " + key_id_cart + "as _id"+ " from " + tablenameCartData + " ORDER BY "+ restaurant_ID + " DESC"+", " + restaurant_name + ", " + restaurant_thumbnail + ", " + dishname + ", " + dish_image + ", " + AreaId + ", " + ItemChoiceIds + ", " + ItemChoiceQty + ", " + ItemId + ", " + Quantity +" DESC" , new String[] {});

答案 3 :(得分:1)

增强版(使用绑定参数减少字符串连接):

Cursor cursor = db.rawQuery
(
    "SELECT ? as _id, ?, ?, ?, ?, ?, ?, ?, ?, ? from " + 
    tablenameCartData + " ORDER BY ? DESC", 
    new String[] 
    {
        key_id_cart, restaurant_ID, restaurant_name, restaurant_thumbnail,
        dishname, dish_image, AreaId, ItemChoiceQty, ItemId, Quantity,
        COLUMN_NAME
     }
);