2013-05-07 81 views
9

我想使用预准备语句来防止SQL SQLite数据库上的SQL注入。然而,当查询包含Like并且与Where name = ? 一起使用时,rawquery会崩溃吗?有没有办法在Android SQLite数据库中使用like和prepared语句?Android SQLite select * from表名%like key%使用预处理语句

这是查询:

它给出了一个绑定或列索引超出范围 谢谢。

+0

您可以检查这在SQL查询中使用的“Like” http://stackoverflow.com/questions/5752575/cant-use-like-clause-in-android-app – 2013-05-07 10:38:54

+1

像将与rawquery工作,能你发布你的代码和日志,以便我们可以看到你得到什么错误... – Vamshi 2013-05-07 10:41:26

回答

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);` 
+0

谢谢,诀窍是通过检查空字符串。拯救了我的一天。在普通查询中,空字符串不会导致问题,但是具有准备好的语句,IT部门。 – 2013-05-08 07:29:04

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); 
+0

我已经尝试过,仍然是同样的问题。 android.database.sqlite.SQLiteBindOrColumnIndexOutOfRangeException:绑定或列索引超出范围:句柄0x1001a58 – 2013-05-07 10:54:07

7

尝试

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

你缺少了 “'” 前后。