Abbas
Abbas

Reputation: 3331

SQLite - Using LIKE Clause with AND Clause

So I needed to search through a TABLE in my Database.

I created a SQLite Query like so

String selection = COLUMN_1 + " LIKE ? AND " + COLUMN_2 + " ?= AND " + COLUMN_3 + " ?=";
String selectionArgs[] = {"%" + value1 + "%", value2 , value3 };

Cursor cursor = db.query(TABLE_1, null, selection, selectionArgs, null, null, null);

I got the following error

SQLiteException: near "?": syntax error (Sqlite code 1): , while compiling: SELECT * FROM TABLE_1 WHERE COLUMN_1 LIKE ? AND COLUMN_2 ?= AND COLUMN_3 ?=, (OS error - 2:No such file or directory)

After trying many different variations and research I gave up and wrote a rawQuery

String query = "SELECT * FROM " + ITEMS_CONTENT_TABLE + " WHERE " + ITEM_NAME + " LIKE '%" + name + "%' AND " + BASE_CATEGORY_NAME + " = '" + baseCategoryName + "' AND " + BASE_CATEGORY_SRC_PATH + " = '" + baseCategorySrcPath + "';";

Cursor cursor = db.rawQuery(query , null);

Which worked seamlessly!

My question is why is the former not working? If it really was syntax error then it shouldn't be working in the later example either.

Upvotes: 1

Views: 862

Answers (2)

Giacomo Lai
Giacomo Lai

Reputation: 494

Change query as below

String selection = COLUMN_1 + " LIKE ? AND " + COLUMN_2 + " =? AND " + COLUMN_3 + " =?"

Upvotes: 2

Moin Khan
Moin Khan

Reputation: 680

Below query is working fine in my case..

 Cursor c = db.rawQuery("Select ConsAcNo From FieldUtilityData Where ConsAcNo like '%" + txtConsAcNo.getText() + "%' and ProjectNo = '" + gp.city + "' and IsCompleted = 'N' and ConsAcNo not in (SELECT CONS_ACCOUNT_NO FROM FieldTestDataFinal) Limit 15", null);

Upvotes: 0

Related Questions