如何从SQLite检索数据?

时间:2018-09-17 09:56:41

标签: android sqlite android-fragments android-sqlite

我正在使用sqlite数据库,在该数据库中,我确定已正确插入sqlite。 现在我正在使用游标从sqlite获取数据,但是当我将数据设置为Texview时,我的应用程序崩溃了。这是我的桌子: 这是我的数据库代码:

SQLiteDatabase db = this.getReadableDatabase();
    String query = "SELECT * FROM " + PRODUCT_TABLE + " WHERE ID = 23";
    Cursor cursor = db.rawQuery(query,null);
    return cursor;

这是我的光标代码:

Cursor cursor = dbHelper.getCheckOutProduct(Id);
        if (cursor != null && cursor.getCount() > 0) {
            do {
                int proId = cursor.getInt(cursor.getColumnIndex("ID"));
                int addressId = cursor.getInt(cursor.getColumnIndex("Price"));
                int paymentTypeID = cursor.getInt(cursor.getColumnIndex("Quantity"));
                int customerID = cursor.getInt(cursor.getColumnIndex("ProductID"));
                Log.e("ProductId",String.valueOf(proId));
            }while (cursor.moveToNext());
        }

我在哪里弄错了?

here is my exception

3 个答案:

答案 0 :(得分:0)

     if (cursor != null && cursor.getCount() > 0) {
           cursor.moveToFirst();
                do {
                    int proId = cursor.getInt(cursor.getColumnIndex("ID"));
                    int addressId = cursor.getInt(cursor.getColumnIndex("Price"));
                    int paymentTypeID = cursor.getInt(cursor.getColumnIndex("Quantity"));
                    int customerID = cursor.getInt(cursor.getColumnIndex("ProductID"));
                    Log.e("ProductId",String.valueOf(proId));
                }while (cursor.moveToNext());
            }

答案 1 :(得分:-1)

SQLiteDatabase db = this.getReadableDatabase();
    String query = "SELECT * FROM " + PRODUCT_TABLE + " where id = 23";
    Cursor cursor = db.rawQuery(query,null);
    return cursor;

我猜这是正确的查询

答案 2 :(得分:-1)

您将从哪里存储从游标检索到的值?为了简便起见,您可以创建一个具有必需属性的模型,并一个一个地设置它,然后返回如下列表:

Cursor cursor = dbHelper.getCheckOutProduct(Id);
List<Model> values = new ArrayList<>();
    if (cursor != null && cursor.getCount() > 0) {
        do {
            int proId = cursor.getInt(cursor.getColumnIndex("ID"));
            int addressId = cursor.getInt(cursor.getColumnIndex("Price"));
            int paymentTypeID = cursor.getInt(cursor.getColumnIndex("Quantity"));
            int customerID = cursor.getInt(cursor.getColumnIndex("ProductID"));

            Model model = new Model();
            model.setProdId(prodId);
            //just like above line set other desired values.                
            values.add(model);
            Log.e("ProductId",String.valueOf(proId));
        }while (cursor.moveToNext());
    }

    return values;

希望这有助于调试问题。