如何从 table 中 select 行?
How do I select rows from table?
我正在制作一个应用程序,其中 MainActivity 有一个包含用户列表的 RecyclerView,例如杂货清单、每周清单等
当用户点击一个项目时,它将导航到产品 activity 也有一个 RecyclerView。我有 2 个不同的 SQLite 数据库 1:lists 2:products.
我使用的逻辑是当用户添加列表时,列表数据库会记录列表名称和id,也会在产品数据库中添加列表名称,当用户添加产品时,我使用 update()
而不是insert()
in SQLite
因为该列已经存在,所以产品名称和id将在产品数据库中更新。
这是列表和产品的结构table:
LISTS
ID LIST_NAME
1 1 list 1
2 2 list 2
PRODUCTS
ID LIST_NAME PRODUCT_NAME
1 1 list 1 product1 in list1
2 2 list 1 product2 in list1
问题是当我添加一个列表然后导航到产品时我看到了这个错误:
android.database.sqlite.SQLiteException: no such column: list (Sqlite code 1 SQLITE_ERROR): , while compiling: SELECT * FROM prducts WHERE LIST_NAME = list, (OS error - 2:No such file or directory)
这是SQLiteOpenHelper
中的方法,错误显示在这一行:cursor = db.rawQuery(productsQuery, null);
public Cursor getAllProducts(String list_name)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if (db != null)
{
String productsQuery = " SELECT * FROM " +DB_TABLE+ " WHERE "+LIST_NAME_COLUMN+ " = "+list_name;
cursor = db.rawQuery(productsQuery, null);
}
return cursor;
}
在产品 activity 中,我使用 Bundle bundle = getIntent().getExtras();
从列表 activity 传递列表名称。在列表 activity 中我使用了 intent.putExtra("list_name", list_name);
您在 sql 语句中传递了字符串 list_name
的值,因此它被视为列名。
在查询中使用 ?
占位符并将 list_name
作为 rawQuery()
的第二个参数传递:
String productsQuery = "SELECT * FROM " + DB_TABLE + " WHERE " + LIST_NAME_COLUMN + " = ?";
cursor = db.rawQuery(productsQuery, new String[] {list_name});
这样您就不必担心引用传递给查询的参数。
我正在制作一个应用程序,其中 MainActivity 有一个包含用户列表的 RecyclerView,例如杂货清单、每周清单等
当用户点击一个项目时,它将导航到产品 activity 也有一个 RecyclerView。我有 2 个不同的 SQLite 数据库 1:lists 2:products.
我使用的逻辑是当用户添加列表时,列表数据库会记录列表名称和id,也会在产品数据库中添加列表名称,当用户添加产品时,我使用 update()
而不是insert()
in SQLite
因为该列已经存在,所以产品名称和id将在产品数据库中更新。
这是列表和产品的结构table:
LISTS
ID LIST_NAME
1 1 list 1
2 2 list 2
PRODUCTS
ID LIST_NAME PRODUCT_NAME
1 1 list 1 product1 in list1
2 2 list 1 product2 in list1
问题是当我添加一个列表然后导航到产品时我看到了这个错误:
android.database.sqlite.SQLiteException: no such column: list (Sqlite code 1 SQLITE_ERROR): , while compiling: SELECT * FROM prducts WHERE LIST_NAME = list, (OS error - 2:No such file or directory)
这是SQLiteOpenHelper
中的方法,错误显示在这一行:cursor = db.rawQuery(productsQuery, null);
public Cursor getAllProducts(String list_name)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if (db != null)
{
String productsQuery = " SELECT * FROM " +DB_TABLE+ " WHERE "+LIST_NAME_COLUMN+ " = "+list_name;
cursor = db.rawQuery(productsQuery, null);
}
return cursor;
}
在产品 activity 中,我使用 Bundle bundle = getIntent().getExtras();
从列表 activity 传递列表名称。在列表 activity 中我使用了 intent.putExtra("list_name", list_name);
您在 sql 语句中传递了字符串 list_name
的值,因此它被视为列名。
在查询中使用 ?
占位符并将 list_name
作为 rawQuery()
的第二个参数传递:
String productsQuery = "SELECT * FROM " + DB_TABLE + " WHERE " + LIST_NAME_COLUMN + " = ?";
cursor = db.rawQuery(productsQuery, new String[] {list_name});
这样您就不必担心引用传递给查询的参数。