Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where clause in SQLite not working in android :(

Tags:

android

sqlite

I'm getting an annoying error when trying to query some data in SQLite.

Here is my code:

Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +" = "+compareToThis, null, null, null, null);

I'm just returning the cursor as a string.

The error is saying:

no such column: compareToThis: while compiling.....the statement

My question is: why is SQLite setting the compareToThis attribute as a column when it's just a value?

How can I fix this?

Thanks in advance.

like image 894
Ernesto Delgado Avatar asked Nov 24 '10 13:11

Ernesto Delgado


2 Answers

Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +" = ?", new String[]{compareToThis},  null, null, null);

The selection must include placeholder for parameter, and the next argument should be the array of parameters.

like image 65
Vladimir Ivanov Avatar answered Oct 31 '22 00:10

Vladimir Ivanov


The solution by Vladimir works, however if you are like me and wonder why your approach did not work initially when it should have, here is why: It is because it expects an integer unless you used (single or double) quotation marks to indicate that it is a string.

For example, in MySql this would return no results:

SELECT * FROM clients WHERE firstName = Bob; -- This will not work.

However when you surround it with quotations, it will return a result because it identifies Bob as a String literal.

Select * FROM clients WHERE firstName = 'Bob'; -- Single quotes work.
Select * FROM clients WHERE firstName = "Bob"; -- Double quotes as well.

Therefore for it to work, you would have to surround your compareToString with single quotes, as Muhhammad mentioned within the comments.

Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +'" = "+compareToThis+"'", null, null, null, null);
like image 33
ChallengeAccepted Avatar answered Oct 31 '22 00:10

ChallengeAccepted