Android 中涉及資料庫查詢的地方一般都會有一個 query() 方法,而這些 query 中有大都(全部?)會有一個參數 selectionArgs,比如下面這個 android.database.sqlite.SQLiteDatabase.query():
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
selection 參數很好理解,就是 SQL 陳述式中 WHERE 後面的部分,即過濾條件, 比如可以為 id=3 AND name='Kevin Yuan' 表示只返回滿足 id 為 3 且 name 為 "Kevin Yuan" 的記錄。
再實際項目中像上面那樣簡單的“靜態”的 selection 並不多見,更多的情況下要在運行時動態產生這個字串,比如
public doQuery(long id, final String name) {<br /> mDb.query("some_table", // table name<br /> null, // columns<br /> "id=" + id + " AND name='" + name + "'", // selection<br /> //...... 更多參數省略<br /> );<br />}
在這種情況下就要考慮一個字元轉義的問題,比如如果在上面代碼中傳進來的 name 參數的內容裡面有單引號('),就會引發一個 "SQLiteException syntax error .... "。
手工處理轉義的話,也不麻煩,就是 String.replace() 調用而已。但是 Android SDK 為我們準備了 selectionArgs 來專門處理這種問題:
public void doQuery(long id, final String name) {<br /> mDb.query("some_table", // table name<br /> null, // columns<br /> "id=" + id + " AND name=?", // selection<br /> new String[] {name}, //selectionArgs<br /> //...... 更多參數省略<br /> );<br /> // ...... 更多代碼<br />}
也就是說我們在 selection 中需要嵌入字串的地方用 ? 代替,然後在 selectionArgs 中依次提供各個用於替換的值就可以了。在 query() 執行時會對 selectionArgs 中的字串正確轉義並替換到對應的 ? 處以構成完整的 selection 字串。 有點像 String.format()。
不過需要注意的是 ? 並不是“萬金油”,只能用在原本應該是字串出現的地方。比如下面的用法是錯誤的:
public void doQuery(long id, final String name) {<br /> mDb.query("some_table", // table name<br /> null, // columns<br /> "? = " + id + " AND name=?", // selection XXXX 錯誤!? 不能用來替換欄位名<br /> new String[]{"id", name}, //selectionArgs<br /> //...... 更多參數省略<br /> );<br /> // ...... 更多代碼<br />}