问题
I'm making an app where MainActivity has a RecyclerView that contains the user's lists e.g. grocery list, weekly list, etc.
When the user clicks on an item, it'll navigate to products activity also has a RecyclerView. I have 2 different SQLite databases 1:lists 2:products.
The logic I used is when a user adds a list, the lists database will record list name and id, also adds list name in products database, and when user add product, I used update()
instead of insert()
in SQLite
because the column already exists, so product name and id will be updated in the product database.
This is the structure of the list and product 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
the problem is when I add a list then navigate to products I see this error :
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)
this is the method inside SQLiteOpenHelper
and the error shows in this line: 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;
}
in product activity i used Bundle bundle = getIntent().getExtras();
to pass the list name from list activity. and in list activity i used intent.putExtra("list_name", list_name);
回答1:
You pass the value of the string list_name
uquoted in the sql statement, so it is considered as a column name.
Use a ?
placeholder in your query and pass list_name
as the 2nd argument of rawQuery()
:
String productsQuery = "SELECT * FROM " + DB_TABLE + " WHERE " + LIST_NAME_COLUMN + " = ?";
cursor = db.rawQuery(productsQuery, new String[] {list_name});
This way you don't need to worry about quoting the parameters that you pass to the query.
来源:https://stackoverflow.com/questions/65370557/how-do-i-select-rows-from-table