我有一个 SQLite 数据库,我想做的是用户选择一个过滤器。例如,我有一个书籍数据库,用户只想查看“Agata christies books”中的数据。
所以我做了一个带有选择选项的微调器,然后我将选择的字段传递给另一个执行查询选择的活动。
我的问题是,如何进行动态查询?认为我有超过 1 个过滤器,我如何根据我通过意图从其他活动传递的数据来创建 WHERE 子句?
谢谢
懒惰但尝试过的方法:
String query = "Select id FROM books WHERE 1=1"
if (condition1) query+= " AND name="+theName;
if (condition2) query+= " AND author="+theAuthor;
if (condition3) query+= " AND price="+thePrice;
如果您可以通过微调器完全控制选项,这是安全的。如果它是一个编辑文本,请使用 preparedStatements 并绑定参数以避免 SQLI。
public Cursor rawQuery (String sql, String[] selectionArgs)
使用
?
生成字符串 SQL 用于绑定并在 selectionArgs 中添加参数。
不确定这是最聪明的方法,但假设你事先知道你可以有 1 个整数过滤器(价格)和 1 个字符串过滤器(作者姓名),我会尝试:
从书中选择* 在哪里 (价格<0 OR AND BOOKS.price = price ) AND (author="" OR BOOKS.author = author);
我不是 SQLite 专家,请检查语法。诀窍就在这里定价< 0 if the filter is not set (hence all lines are taken into account since condition price<0 is true), and set author as an empty string to not to filter on the author (SELECT will not filter out these lines since condition is true).
这行得通!
boolean filterName = false;
boolean filterPrice = false;
ArrayList<String> selectionArgs = new ArrayList<String>();
String query = "SELECT * FROM BOOKS WHERE 1=1";
if(filterName) {
selectionArgs.add(searchString);
query += " AND NAME = ?";
}
if(filterPrice) {
selectionArgs.add(priceString);
query += " AND PRICE= ?";
}
Cursor c = m_Database.rawQuery(query, (String[])selectionArgs1.toArray());
试试这个,我以学生数据为例
public ArrayList<Student>getStudent(int stdID,String stdName)
{
ArrayList<Student> studentArr = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
String sqlQuery = "SELECT * FROM tblstudent WHERE 1=1";
String sqlParam = "";
/*Here we're building the dynamic sql.*/
if(stdID > 0)
{
sqlQuery += " AND std_id = ?";
sqlParam = String.valueOf(stdID);
}
if(!stdName.trim().isEmpty())
{
sqlQuery += " AND std_name = ?";
sqlParam = stdName.trim();
}
/*Do this to avoid SQL injection Attack (SIA) [it's very important!]*/
sqlParam = sqlParam.replaceAll(";|--","");
if (db != null) {
if (!sqlParam.isEmpty()) {
cursor = db.rawQuery(SQL,new String[]{sqlParam});
}else {
/*if the "sqlParam" is empty.*/
cursor = db.rawQuery(SQL,null);
}
if (cursor != null && cursor.getCount()>0) {
while(cursor.moveToNext()){
Student stdmodel = new Student();
stdmodel.setstdID(cursor.getInt(0));
stdmodel.stdName(cursor.getString(1));
studentArr.add(stdmodel);
}
cursor.close();
}
}
return studentArr;
}