Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to use prepared statements to prevent sql injections on Android SQLite database. However, rawquery crashes when the query contains Like and works with Where name = ? is there a way to use like and prepared statements in Android SQLite db ?

This is the query:

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 + "%"});

it gives a bind or column index out of range Thank you.

like image 954
Abdellah Benhammou Avatar asked May 07 '13 10:05

Abdellah Benhammou


3 Answers

Try

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

You are missing the " ' " before and after.

like image 196
Anirudha Agashe Avatar answered Oct 17 '22 02:10

Anirudha Agashe


    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);`
like image 20
Digvesh Patel Avatar answered Oct 17 '22 01:10

Digvesh Patel


Try like..

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);
like image 1
Talha Avatar answered Oct 17 '22 02:10

Talha