1

请让我知道为什么我的 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

4 回答 4

9

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

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

我认为这种方式更安全。

于 2012-12-26T14:46:07.977 回答
8

尝试...(您之前遗漏了双引号where

Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" +categoryex + "'" , null);
于 2012-12-26T14:31:04.343 回答
2

你的报价被窃听了:

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

您还应该阅读SQL 注入攻击。

于 2012-12-26T14:33:02.627 回答
1

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

 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;
}
于 2015-08-11T10:54:43.510 回答