user2312945 user2312945 - 25 days ago 15
Android Question

like operator syntax in sqlite with android

I'm developing with Android and I need to do a query with sqlite using the like operator and variables.

The piece of code I just try to modify is, the implementation of a database present at this link.

So, I'm trying to do a query on the table created in the link in order to select just a name from a table. I'm doing like this:

Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " +
SAMPLE_TABLE_NAME + " where" +field+ " like %"+search+"%" , null);


where field and search are two variable defined above in this way:

final String field = "LastName";
final String search = "Makam";


If I execute the app in output, I should see a row with the name and age that I have selected in the query.But, I obtain nothing!!!

The
Logcat of Eclipse
shows :

sqlite returned: error code = 1,msg = near "like": syntax error.


But I'm pretty sure the syntax it' s correct. Could someone help me?

Answer

use this way:

Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " +
SAMPLE_TABLE_NAME + " where " +field+ " like '%"+search+"%'" , null);

Edited: create function

public Cursor getSearch(String SAMPLE_TABLE_NAME, String field,
            String search) {
        SQLiteDatabase sampleDB = this.getReadableDatabase();
        Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM "
                + SAMPLE_TABLE_NAME + " where " + field + " like '%" + search
                + "%'", null);
        return c;
    }
Comments