SQLite动态查询

bqjvbblv  于 2023-05-18  发布在  SQLite
关注(0)|答案(5)|浏览(233)

我有一个SQLite数据库,我想做的是用户选择一个过滤器。例如,我有一个书籍数据库,用户只想从“Agata Christies Books”中查找数据。
因此,我创建了一个包含要选择的选项的微调器,然后将所选字段传递给另一个执行查询select的Activity。
我的问题是,如何进行动态查询?假设我有多个过滤器,我如何使子句WHERE取决于我通过Intent从其他Activity传递的数据?
谢谢

jgovgodb

jgovgodb1#

懒惰的方式,但尝试和真实:

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;

如果你通过微调器完全控制选项,这是安全的。如果是edittext,使用preparedStatements并绑定参数以避免SQLI。

nmpmafwu

nmpmafwu2#

public String strategy(String strategy,String[] strategy)
使用?生成String SQL用于绑定,并在selectionArgs中添加参数。

xtfmy6hx

xtfmy6hx3#

不确定这是最聪明的方法,但假设你事先知道你可以有1个整数过滤器(价格)和1个字符串过滤器(作者姓名),我会试试:
SELECT * FROM BOOKS WHERE(price<0 OR AND BOOKS.price = price)AND(author="”OR BOOKS.author = author);
我不是SQLiteMaven,请检查语法。这里的技巧是,如果没有设置过滤器,则设置price < 0(因此所有行都被考虑在内,因为条件price<0为true),并将author设置为空字符串,以不过滤作者(SELECT不会过滤掉这些行,因为条件为true)。
这会成功的!

lmvvr0a8

lmvvr0a84#

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());
xu3bshqb

xu3bshqb5#

试试这个,我用学生数据作为例子

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;
}

相关问题