Search code examples
androidsqlitesqliteopenhelper

SQLite Database query function not replacing the ? with selection args


i have a get function in my database class to get a specific line from the DB.

 public Line getLine(String date){
    SQLiteDatabase sql = db.getWritableDatabase();
    Cursor cursor;
    Line line = new Line();
    try{
        cursor = sql.query(Db_name,null,DATE_COL+"=?",new String[] {date},null,null,null);
        line = new Line(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3).equals("YES"));
    }
    catch (Exception e){
        e.getCause();
    }
    finally {
        if (sql.isOpen())
            sql.close();
    }
    return line;
}`

however when i run it, the cursor is not getting the right query, when debbuging it looks like this:

SQLiteQuery: SELECT * FROM a28a9a2015 WHERE date_col=?

so it kept the ? and did not put the date string in there.. i've tried something like -

 cursor = sql.query(Db_name,null,DATE_COL+"="+date,null,null,null,null);

OR

 cursor = sql.query(Db_name,null,DATE_COL+"= '"+date+"',null,null,null,null);

with same result.

any pointers?


Solution

  • You need to move cursor to first position

    cursor = sql.query(Db_name,null,DATE_COL+"=?",new String[] {date},null,null,null);
    if (cursor.moveToFirst()) {
         // TODO
    }
    

    Otherwise your cursor is in position -1 and cannot get any data. Symbol "?" is replacing inside request to sqlite so in cursor you'll see "?".