Android数据库获取数据库值

时间:2017-02-14 12:22:28

标签: android database sqlite

我在该表中有一个表有一列,我已将该列的默认值设置为0;但每当我访问该值时,它无法访问。以下代码,我尝试过。

 public void getmaxoid() {
        SQLiteDatabase database = dataforcategorylistview.getReadableDatabase();
        String[] columns = {"order_id"};
        Cursor cursors = database.rawQuery("Select max(order_id) from sales_item", null);
        if (cursors.moveToNext()) {
            convertedorderid = cursors.getInt(cursors.getColumnIndexOrThrow("order_id"));

            if (convertedorderid==0) {
                int oid = 0;
                //int oid = Integer.parseInt(OrderIdFromService);
                serverorderid = String.valueOf(convertedorderid++);
                orderidset.setText(serverorderid);
            } else {

                serverorderid = String.valueOf(convertedorderid++);
                orderidset.setText(serverorderid);
            }
            cursors.close();
        }

    } And this is my table: 
String salesitem = "CREATE TABLE `sales_item` (`sales_id` integer NOT NULL,`order_id` numeric DEFAULT 0,`menu_id`   nvarchar(500) NOT NULL,`qty`    integer NOT NULL,`rate` numeric NOT NULL,`total_amount` numeric NOT NULL,`w_id` numeric NOT NULL,`kot_id`   integer NOT NULL,PRIMARY KEY(`sales_id`))";

2 个答案:

答案 0 :(得分:0)

将您的查询更改为

Cursor cursors = database.rawQuery("Select max(order_id) as max_order_id from sales_item", null);

convertedorderid = cursors.getInt(cursors.getColumnIndexOrThrow("max_order_id"));

答案 1 :(得分:0)

光标中的列名称类似于max(order_id)。如果只有一列,则可以对列索引进行硬编码:

convertedorderid = cursors.getInt(0);

无论如何,使用helper function来读取查询的单个结果值会更容易:

long max_id = DatabaseUtils.longForQuery(database,
        "Select max(order_id) from sales_item", null);