I am using the query method of SQLiteDatabase. How do I use the query method?
I tried this:
Cursor cursor = sqLiteDatabase.query(
tableName, tableColumns, whereClause, whereArgs, groupBy, having, orderBy);
tableColumns – columns parameter is constructed as follows.
String[] columns = new String[]{KEY_ID, KEY_CONTENT};
If we need to get all the fields, how should the column parameter to be constructed. Do we need to include all the Field Names in String array?
How do I properly use the query method?
tableColumns
nullfor all columns as inSELECT * FROM ...new String[] { "column1", "column2", ... }for specific columns as inSELECT column1, column2 FROM ...– you can also put complex expressions here:new String[] { "(SELECT max(column1) FROM table1) AS max" }would give you a column namedmaxholding the max value ofcolumn1whereClause
WHEREwithout that keyword, e.g."column1 > 5"?for things that are dynamic, e.g."column1=?"-> seewhereArgswhereArgs
?inwhereClausein the order they appearthe others
whereClausethe statement after the keyword ornullif you don’t use it.Example
is equivalent to the following raw query
By using the Where/Bind -Args version you get automatically escaped values and you don’t have to worry if input-data contains
'.Unsafe:
String whereClause = "column1='" + value + "'";Safe:
String whereClause = "column1=?";because if value contains a
'your statement either breaks and you get exceptions or does unintended things, for examplevalue = "XYZ'; DROP TABLE table1;--"might even drop your table since the statement would become two statements and a comment:using the args version
XYZ'; DROP TABLE table1;--would be escaped to'XYZ''; DROP TABLE table1;--'and would only be treated as a value. Even if the'is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to buildintand other primitives directly intowhereClausethough)