Search code examples
androidandroid-sqlitewhere-in

Android SQL Query multiple WHERE args


For some reason my sql.query is failing because of the way it is formatted. I have no idea why. It does not crash nor does it throw an error. It simply does not return a value. I am using two WHERE arguments in the query. I see in the Log.d that both arguments are successfully passed to the method.

public static String fetchLightTableD(String flightRowId, String filenamePrefix){

    String[] lightcolumns = new String[] { KEY_ROWID, KEY_TID, KEY_NAME, KEY_LUXVALUE, KEY_TRANSMITTED };
    Log.d("CSV", "SQL fetchLightTableD, revceived tid - " + filenamePrefix + " " + flightRowId);
    Cursor lightcursor = myDatabase.query(LIGHT_TABLE, lightcolumns, KEY_TID + "=" + filenamePrefix + " AND " + KEY_ROWID + "=" + flightRowId, null, null, null, null);
    String lightTableResults = "";

    int iRowId = lightcursor.getColumnIndex(KEY_ROWID);
    int iTid = lightcursor.getColumnIndex(KEY_TID);
    int iName = lightcursor.getColumnIndex(KEY_NAME);
    int iLux = lightcursor.getColumnIndex(KEY_LUXVALUE);
    int iTrans = lightcursor.getColumnIndex(KEY_TRANSMITTED);

    for (lightcursor.moveToFirst(); !lightcursor.isAfterLast(); lightcursor
            .moveToNext()) {
        lightTableResults = lightTableResults
                + lightcursor.getString(iRowId) + ","
                + lightcursor.getString(iTid) + ","
                + lightcursor.getString(iName) + ","
                + lightcursor.getString(iLux) + ","
                + lightcursor.getString(iTrans) + "\n";


    }

    return lightTableResults;

}

It should be filtering the table for the row that matches both the rowid and the filenameprefix. I have also tested removing one or the other WHERE args to make sure values actually exist. Of course they do, so there is something wrong with my AND. Can anyone see where it is incorrect?

The equivalent should be as so:

SELECT lightcolumns 
FROM LIGHT_TABLE 
WHERE KEY_TID=rowid AND KEY_TID=filenamePrefix;

Solution

  • Use your query like this

     Cursor lightcursor = myDatabase.query(LIGHT_TABLE,lightcolumns,
                KEY_TID "=?"+ " AND " + KEY_ROWID +"=?",
                new String[] { filenamePrefix , flightRowId},null, null, null);
    

    instead of

    Cursor lightcursor = myDatabase.query(LIGHT_TABLE, lightcolumns, KEY_TID + "=" + filenamePrefix + " AND " + KEY_ROWID + "=" + flightRowId, null, null, null, null);