Android SQLite查询:麻烦WHERE子句

时间:2012-12-26 14:28:28

标签: android where-clause sqlite

请让我知道为什么我的where子句不起作用。我尝试使用查询而不是rawquery,但没有运气。

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

4 个答案:

答案 0 :(得分:9)

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

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

我认为这样更安全。

答案 1 :(得分:8)

尝试...(你在where之前省略了双引号。

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

答案 2 :(得分:2)

你的报价有误:

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

您还应该阅读SQL injection次攻击。

答案 3 :(得分: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;
}