buggydroid
buggydroid

Reputation: 1870

Android SQLite Query: Trouble with WHERE clause

Please let me know why my where clause isn't working. I tried using the query instead of rawquery but no luck.

    try {
        String categoryex = "NAME";
        DBHelper dbHelper = new DBHelper(this.getApplicationContext());
        MyData = dbHelper.getWritableDatabase();

        Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + where Category = '+categoryex'" , null);
        if (c != null ) {
            if  (c.moveToFirst()) {
                do {
                    String firstName = c.getString(c.getColumnIndex("Category"));
                    String age = c.getString(c.getColumnIndex("Text_Data"));
                    results.add(  firstName + " Directions: " + age);
                }while (c.moveToNext());
            } 
        }           
    } catch (SQLiteException se ) {
        Log.e(getClass().getSimpleName(), "Could not create or Open the database");
    } finally {
        if (MyData != null) 
            MyData.execSQL("DELETE FROM " + tableName);
            MyData.close();
    }   

Upvotes: 1

Views: 18486

Answers (4)

Ameen Maheen
Ameen Maheen

Reputation: 2737

it will be more easy if you use this technique instead of rawQuery,its easy way change your table name, columns and where conditions accordingly.

 public ArrayList<Invitees> getGroupMembers(String group_name) {

    ArrayList<Invitees> contacts = new ArrayList<>();

    SQLiteDatabase db = this.getReadableDatabase();

    String[] projection = {COLUMN_CONTACT, COLUMN_PHONE_NUMBER};

    String selection = COLUMN_GROUP_NAME + "=?";

    String[] selectionArgs = {group_name};

    Cursor cursor = db.query(GROUPS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);

    if (cursor.moveToFirst()) {

        do {
            Invitees invitees = new Invitees();

            invitees.setUserName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)));

            invitees.setInviteePhone(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHONE_NUMBER)));

            contacts.add(invitees);

        } while (cursor.moveToNext());

    }
    return contacts;
}

Upvotes: 1

gezimi005
gezimi005

Reputation: 381

I think you should use rawQuery in this form:

rawQuery("SELECT * FROM ? where Category = ?", new String[] {tableName, categoryex});

I think it's more secure this way.

Upvotes: 9

Slippery Pete
Slippery Pete

Reputation: 3110

Your quotes are buggered:

Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" + categoryex + "'" , null);

You also should read up on SQL injection attacks.

Upvotes: 2

David M
David M

Reputation: 2541

try... (you left out a double-quote before where.

Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" +categoryex + "'" , null);

Upvotes: 10

Related Questions