tableColumns
null 对于所有列 SELECT * FROM ...
new String[] { "column1", "column2", ... }对于特定的列,例如SELECT column1, column2 FROM ...-您还可以在此处放置复杂的表达式:
new String[] { "(SELECT max(column1) FROM table1) AS max" }将为您提供一列max,其中包含column1
条款
- 您
WHERE没有该关键字的部分,例如"column1 > 5"
- 应该包括
?动态的东西,例如"column1=?"-> seewhereArgs
whereArgs
- 指定填充每个内容
?中whereClause的出现顺序
其他
- 就像
whereClause关键字后面的语句一样,或者null如果您不使用它。
例
String[] tableColumns = new String[] {
"column1",
"(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
"value1",
"value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
null, null, orderBy);
// since we have a named column we can do
int idx = c.getColumnIndex("max");
等效于以下原始查询
String queryString =
"SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
"WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);
通过使用Where / Bind -Args版本,您可以自动转义值,而不必担心输入数据是否包含'。
不安全:String whereClause = "column1='" + value + "'";
安全:String whereClause = "column1=?";
因为如果value包含一条'语句,则该语句可能会中断并导致异常或发生意外情况,例如,value = "XYZ'; DROP TABLE table1;--"甚至可能会删除表,因为该语句将成为两个语句和一个注释:
SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'
使用args版本XYZ'; DROP TABLE table1;--将被转义为'XYZ''; DROP TABLE table1;--'并且仅被视为值。即使'不是为了做坏事,人们还是经常在名称中使用它,或者在文本,文件名,密码等中使用它。因此,请始终使用args版本。(虽然可以int直接构建和其他原语whereClause)