Select query in SQLite?

2.3k Views Asked by At

I'm making use of the function to retrieve one value from the table,

public ArrayList selectValue(SQLiteDatabase sqliteDB, String contactEmail){
        Cursor c = sqliteDB.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE ContactEmail='"+contactEmail+"'",null);
        if (c != null ) {
            if  (c.moveToFirst()) {
                do {
                    double contactId = c.getDouble(c.getColumnIndex("ContactId"));
                    results.add("ContactEmail: " +contactEmail+ ",ContactId: " + contactId);
                }while (c.moveToNext());
            } 
        }
        return results;
    }

But the above function retrieves all the values from the table.. Not sure what is wrong with the query..

I also tried hardcoding the value like this,

Cursor c = sqliteDB.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE ContactEmail='[email protected]'",null);

but this also gives all the rows. Am I missing something here?? Please help

2

There are 2 best solutions below

0
On

Thanks for your response folks.. I fixed the problem..

This is how I changed the code and got it worked,

public String selectValue(SQLiteDatabase sqliteDB, String contactEmail){

        String contactId="Nothing";

        Cursor c = sqliteDB.rawQuery("SELECT * FROM " + TABLE_NAME + " where ContactEmail = '"+contactEmail+"'", null);
        if (c != null ) {
            if  (c.moveToFirst()) {
                contactId = c.getString(c.getColumnIndex("ContactId"));
            }   
        }
        return contactId;
    }

Thanks again!! Have a great day!!

1
On

Try to do it like this:

    SQLiteDatabase mDb;
    DataBaseHelper mDbHelper;
    mDbHelper = new DataBaseHelper(context);
    mDb = mDbHelper.getWritableDatabase();
    Cursor cursor = mDb.query(TABLE_NAME, null, ContactEmail + " =? ", new String[] { "[email protected]" }, null, null, null);
    //Continue with your code


private static class DataBaseHelper extends SQLiteOpenHelper {

        /* Create a helper object to create, open, and/or manage a database */
        DataBaseHelper(Context context) {
            super(context, TABLE_NAME, null, DATABASE_VERSION);
        }

        /* Called when the database is created for the first time */
        @Override
        public void onCreate(SQLiteDatabase db) {
                     //Your code
        }

            /* Called when the database needs to be upgraded*/ 
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                      //Your code
        }
}