场景:
今天在写代码的时候被责令重构,凡是使用rawQuery的地方一律改为使用query,原因无他,可防sql注入,并且由于query的参数一段段都是分开的,所以推荐使用Query。
比如我要查询我数据库里某张表最后一条状态为onGoing状态的数据代码如下:
- rawQuery
自己拼接sql语句,一不小心就会写错.
- Query
/** * get last ongoing visit in database. * @return */ public Visit getLastOngoingVisit() { String[] columns = null; String selection = VisitDB.Visit.COLUMN_STATUS + "=?"; String[] selectionArgs = {String.valueOf(Visit.STATUS_ONGOING)}; String orderby = VisitDB.Visit.COLUMN_ANDROID_ID+" DESC"; String limit = "1"; Cursor cursor = database.query(table,columns,selection,selectionArgs,null,orderby,limit); cursor.moveToFirst(); return cursorToEntity(cursor); }
这样似乎很清晰吧
关于query各个参数说明
/** * Query the given table,returning a {@link Cursor} over the result set. * * @param table The table name to compile the query against. * @param columns A list of which columns to return. Passing null will * return all columns,which is discouraged to prevent reading * data from storage that isn't going to be used. * @param selection A filter declaring which rows to return,formatted as an * sql WHERE clause (excluding the WHERE itself). Passing null * will return all rows for the given table. * @param selectionArgs You may include ?s in selection,which will be * replaced by the values from selectionArgs,in order that they * appear in the selection. The values will be bound as Strings. * @param groupBy A filter declaring how to group rows,formatted as an sql * GROUP BY clause (excluding the GROUP BY itself). Passing null * will cause the rows to not be grouped. * @param having A filter declare which row groups to include in the cursor,* if row grouping is being used,formatted as an sql HAVING * clause (excluding the HAVING itself). Passing null will cause * all row groups to be included,and is required when row * grouping is not being used. * @param orderBy How to order the rows,formatted as an sql ORDER BY clause * (excluding the ORDER BY itself). Passing null will use the * default sort order,which may be unordered. * @param limit Limits the number of rows returned by the query,* formatted as LIMIT clause. Passing null denotes no LIMIT clause. * @return A {@link Cursor} object,which is positioned before the first entry. Note that * {@link Cursor}s are not synchronized,see the documentation for more details. * @see Cursor */对于sqlite的limit跟MysqL还是有区别的,有个offset关键字,可忽略多少条记录进行查询多少条数据,具体的不赘述,自己实验使用吧。