vendredi 10 juillet 2015

How to use string field in where clause in android sqlite

I have on sqlite table tb_expense with String user_id field as primary key. I am inserting to this table using Contentvalues like this

      `ContentValues values = new ContentValues();

        values.put(KEY_USER_ID, DatabaseUtils.sqlEscapeString(expense.getUser_id()));

        values.put(KEY_DATE , DatabaseUtils.sqlEscapeString(date));

        values.put(KEY_AMOUNT , expense.getAmount());

        values.put(KEY_PARTICULARS , DatabaseUtils.sqlEscapeString(expense.getParticulars()));

        values.put(KEY_PLACE, DatabaseUtils.sqlEscapeString(expense.getPlace()));

        long expense_id = db.insert(TABLE_EXPENSE , null ,values);

Insertion is perfect and I am able to print the expense_id using Log.e But the problem is while retrieving from this table ;

When I retrieve whole data from tbl_expense without any condition , Its works fine .

        String query = "SELECT * FROM "+TABLE_EXPENSE;

        Cursor c =  db.rawQuery(query,null);

Above query works fine and I am able to get whole data;

But when I try to retrieve expense of one single user with id in where clause , it retrieves nothing. Here is my code

       String query = "SELECT * FROM "+TABLE_EXPENSE +" WHERE "+ KEY_USER_ID+" = '"+ user.getId() +"'";

        Cursor c =  db.rawQuery(query,null);

and Log.e prints the Query like this

    SELECT * FROM tbl_expense WHERE user_id = 'USR107672'

I think the query is correct , and also USR107672 exists in db , because without where clause this record was getting. What is the error here?

I also tried using db.query like this

      Cursor c = db.query

                (

                        TABLE_EXPENSE,

                        new String[] {  KEY_USER_ID, KEY_PARTICULARS , KEY_AMOUNT , KEY_DATE , KEY_PLACE },

                        KEY_USER_ID + " = ? " ,

                        new String[] { user.getId()},

                        null, null, null

                );

 but this also didn't work. 

Aucun commentaire:

Enregistrer un commentaire