2012-12-26 35 views
1

请让我知道为什么我的where子句不起作用。我尝试使用查询而不是rawquery,但没有运气。Android SQLite查询:WHERE子句出现问题

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(); 
    } 
+0

有什么问题 –

+1

使用查询。记录你的例外。发布您的预期/实际结果 – njzk2

回答

8

尝试......(你where之前留下了一个双引号

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

你的报价是累垮:

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

你也应该SQL injection攻击阅读起来。

+0

非常感谢.. :)我感谢您的帮助。有一段时间以来一直在挖这个。我希望我能接受你的答案! – buggydroid

9

我认为你应该在这种形式下使用rawQuery

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

我认为这样更安全。

1

如果使用这种技术而不是rawQuery,它会更容易,它的简单方法就是相应地更改表名,列和条件。

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; 
}