Android SQLite select * from table where name like%key%using prepared statements

时间:2013-05-07 10:31:45

标签: android sqlite exception prepared-statement

我想使用预准备语句来阻止Android SQLite数据库上的sql注入。但是,当查询包含Like并与Where name = ?一起使用时,rawquery崩溃 有没有办法在Android SQLite db中使用like和prepared语句?

这是查询:

sqlQuery = "SELECT * FROM " + TABLE_CALLS + " where " + CALLER_NAME + " like ? COLLATE NOCASE or " + CALLER_NBR + " like ? or " + CALLER_EXT + " like ?" + " or " + IS_OUTGOING + " like ?  COLLATE NOCASE or " + TYPE + " like ? COLLATE NOCASE";

Cursor cursor = database.rawQuery(sqlQuery, new String[]{"%" + criterion + "%", "%" + criterion + "%","%" + criterion + "%","%" + criterion + "%","%" + criterion + "%"});

它使绑定或列索引超出范围 谢谢。

3 个答案:

答案 0 :(得分:21)

    if (name.length() != 0) {

        name = "%" + name + "%";
    }
    if (email.length() != 0) {
        email = "%" + email + "%";
    }
    if (Phone.length() != 0) {
        Phone = "%" + Phone + "%";
    }
    String selectQuery = " select * from tbl_Customer where Customer_Name like  '"
            + name
            + "' or Customer_Email like '"
            + email
            + "' or Customer_Phone like '"
            + Phone
            + "' ORDER BY Customer_Id DESC";

    Cursor cursor = mDb.rawQuery(selectQuery, null);`

答案 1 :(得分:7)

尝试

Cursor cursor = database.rawQuery(sqlQuery, new String[]{"'%" + criterion + "%'", 
   "'%" + criterion + "%'",
   "'%" + criterion + "%'",
   "'%" + criterion + "%'",
   "'%" + criterion + "%'"});

你错过了之前和之后的“'”。

答案 2 :(得分:1)

试试..

String[] a = new String[5];
a[0]       = '%' + criterion + '%';
a[1]       = '%' + criterion + '%';
a[2]       = '%' + criterion + '%';
a[3]       = '%' + criterion + '%';
a[4]       = '%' + criterion + '%';
Cursor cursor = database.rawQuery(sqlQuery,a);