-2

I have a small function for checking to see if a records already exists in my sqlite database. There is data in the database that should match the query, i have verified this by opening up the database.But i get an empty result.

Below is the function, it takes in a parameter and uses that as the search parameter. i have also verified that the parameter is correct.

public boolean checkParent(String email)
{
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = null;

    try
    {
        res = db.rawQuery("SELECT * FROM parents WHERE email = ' " + email + " ' ",null);
        res.close();
    }
    catch (Exception ex)
    {
        Log.e("Error checking parent", ex.toString());
    }

    if(res == null)
    {
        return true;
    }
    else
    {
        return false;
    }
}
lagfvu
  • 597
  • 6
  • 21
  • 3
    Remove the spaces arond before and after `email` or even better used Pepared statements. No email in your DB starts and ends with a space I guess – juergen d Sep 10 '16 at 11:44
  • use `SELECT * FROM parents WHERE email = ?` and pass `saelectionArgs` to `rawQuery` method – pskink Sep 10 '16 at 11:46
  • 2
    You are closing cursor and then accessing the cursor. will it work? – Nikhil Sep 10 '16 at 11:48

2 Answers2

1

Right way to pass argument in rawQuery method.

db.rawQuery("SELECT * FROM parents WHERE email = ?",new String[]{email});
brahmy adigopula
  • 617
  • 3
  • 15
Yogesh Lakhotia
  • 888
  • 1
  • 13
  • 26
1

You are checking whether the cursor object res is null. This will never happen; rawQuery() always returns a cursor object.

You have to check whether the cursor is empty, i.e., whether the cursor actually contains any rows. To do this, call a method like moveToFirst() and check if it succeeds.

Or even better, use a helper function that does handle the cursor for you:

public boolean checkParent(String email)
{
    SQLiteDatabase db = this.getReadableDatabase();
    long count = DatabaseUtils.queryNumEntries(db,
            "parents", "email = ?", new String[]{ email });
    return count > 0;
}
CL.
  • 173,858
  • 17
  • 217
  • 259