Search code examples
android-sqlite

How to use android SQLITE SELECT with two parameters?


This code return empty cursor.What is wrong here? Data is already there in sqlitedb.

public static final String COL_2 =  "ID";
    public static final String COL_3 = "TYPE";

public Cursor checkData(String id, String type){
    SQLiteDatabase db = getWritableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM "+ TABLE_NAME  + " WHERE " + COL_2 + " = " + id+ " AND " + COL_3 + " = " + type , null);
    return res;
}

Solution

  • When you pass strings as parameters you must quote them inside the sql statement.
    But by concatenating quoted string values in the sql code your code is unsafe.

    The recommended way to do it is with ? placeholders:

    public Cursor checkData(String id, String type){
        SQLiteDatabase db = getWritableDatabase();
        String sql = "SELECT * FROM "+ TABLE_NAME  + " WHERE " + COL_2 + " = ? AND " + COL_3 + " = ?";
        Cursor res = db.rawQuery(sql , new String[] {id, type});
        return res;
    }
    

    The parameters id and type are passed as a string array in the 2nd argument of rawQuery().