2013-03-07 82 views
0

我想寫一個SQL數據庫請求使用.query而不是.rawQuery(我已被告知它更有效率,即使不是每個人似乎都同意這一點...)。如何使用rawQuery()而不是query()來編寫此請求? (代碼裏面)

如果我把它寫在SQL,這將是大約是這樣的:

select COL_NAME, COL_COMMENTS, KEY_ROW_ID 
from TABLE 
where COL_CAT1 = myVariable1 or myVariable2 or ... myVariableN 
or COL_CAT2 = myVariable1 or myVariable2 or .... myVariableN 
or COL_CAT3 = myVariable1 or myVariable2 or.... myVariableN 

我已經試過這樣:

public Cursor findNameInTable(int myVariable1, int myVariable2, int myVariableN) { 
    String where = COL_CAT1 + " = ? OR " + COL_CAT2 + "=?"; 
    String[] whereArgs = new String[] { Integer.toString(myVariable1), Integer.toString(myVariable2), Integer.toString(myVariableN)}; 
    c = myDatabase 
      .query(DATABASE_TABLE, new String[] { KEY_ROWID, COL_NAME , COL_COMMENTS }, 
        where, 
        whereArgs, null, 
        null, null); 
    return c; 
} 

這樣做的問題是,該系統正在做這個:

select ..... 
    from ..... 
    where COL_CAT1 = myVariable1 
    or COL_CAT2 = myVariable2 
    or ???? = myVariableN 

然後它崩潰,因爲它期望比較每個變量與ne w列,這不是我想要的:我有更多的輸入變量比列。

它實際上是「=?」這似乎不合適,但沒有辦法找到如何編寫這種請求,大多數文檔是關於rawQuery()而不是query()。提前致謝。

回答

1

試試這個

public Cursor findNameInTable(int myVariable1, int myVariable2, ..., int myVariableN) 
{ 
    String inInterval = "(?,?,?,...,?)"; // N question mark altogether. 
    String where = COL_CAT1 + " IN " + inInterval 
        + " OR " + COL_CAT2 + " IN " + inInterval 
        + ........... 
        + " OR " + COL_CATM + " IN " + inInterval; 
int numberOfColumn = M; // The number of columns you have. 
String[] whereArgs = new String[M * N]; 
for (int i = 0; i < M; i++) 
{ 
    whereArgs[i * N + 0] = Integer.toString(myVariable1); 
    whereArgs[i * N + 1] = Integer.toString(myVariable2); 
    whereArgs[i * N + 2] = Integer.toString(myVariable3); 
     ........................ 
    whereArgs[i * N + N - 1] = Integer.toString(myVariableN); 
} 
Cursor c = myDatabase 
     .query(DATABASE_TABLE, new String[] { KEY_ROWID, COL_NAME , COL_COMMENTS }, 
       where, 
       whereArgs, null, 
       null, null); 
    return c; 
} 
+0

感謝您的建議,它仍然存在問題,因爲它只適用於有多少myVariable列(給我一個「綁定或列索引超出範圍),在我的應用程序中,我將只有一個很少的列和很多的變量,但無論如何,它比我所擁有的要好,因爲它確實將每列的值與所有變量進行比較! 我會嘗試修改你的代碼以使其工作並適合於我的期望 – Phalanx 2013-03-08 02:48:10

+0

我更新了我的答案,它應該適用於變量M列 – 2013-03-08 03:08:15

+0

是的,絕對!我經過一番嘗試後才發現,並且正準備在這裏寫下它!很好,非常感謝你的幫助,我真的很感謝欣賞!=) – Phalanx 2013-03-08 03:21:05

相關問題