Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite Select Query with rawQuery at Android

Tags:

android

sqlite

I know it is a basic question, but i can not find problem. I try to get some columns with rawQuery.

    SQLiteDatabase db=database.getReadableDatabase();

    try 
    {
       String sql="SELECT * FROM CAR WHERE name = "; 
       Cursor crs = db.rawQuery(sql+"5P", null);
    }

I always get the same exception.

android.database.sqlite.SQLiteException: **unrecognized token**: "5P": , while compiling: SELECT * FROM CAR WHERE name = 5P

I have 5P at CAR table, i am sure because i used it other queries.

like image 396
Anil Kocabiyik Avatar asked Apr 21 '13 22:04

Anil Kocabiyik


People also ask

What is RawQuery in Android SQLite?

On the other hand, RawQuery serves as an escape hatch where you can build your own SQL query at runtime but still use Room to convert it into objects. RawQuery methods must return a non-void type. If you want to execute a raw query that does not return any value, use RoomDatabase#query methods.

What is the difference between query and RawQuery in Android?

RawQuery is for people who understand SQL and aren't afraid of it, query is for people who don't.

What is a cursor in Android?

Cursors are what contain the result set of a query made against a database in Android. The Cursor class has an API that allows an app to read (in a type-safe manner) the columns that were returned from the query as well as iterate over the rows of the result set.

What is cursor moveToFirst?

Cursor is an object that can iterate on the result rows of your query. Cursor can moves to each row. . moveToFirst() method move it to the first row of result table.


1 Answers

You either need to quote that value, or better yet, use positional parameters:

String[] args={"5P"};
Cursor crs=db.rawQuery("SELECT * FROM CAR WHERE name = ?", args);

The advantage of using positional parameters is that SQLite will handle quoting the string, escaping any embedded quotes, etc.

like image 69
CommonsWare Avatar answered Nov 03 '22 09:11

CommonsWare