我们都知道在有涉及数据库的应用中,查找的操作是必不可少的。android 的SQLiteDatabase
类有自带的query方法,很好用。现在我就写一写记录一下。
之前对android数据库的操作是比较担忧的。也说不出什么所以然来,原因可能就是自己之前没有在项目中实际的操作过数据库(android的数据库),对它的Sql语句怎么写,怎么操作是比较朦胧的,所以心里上就有点没底(不知彼,心没底,就害怕)。后来在自己实际操作之后发现,它的Sql语句没有什么特殊的,很简单,只是帮我们略写了whereClause语句(记住,你不用去写where这个关键字,而只要写出你的逻辑判断语句)。另一个就是判断的参数whereArgs
.它是一个数组,这里的设计是很巧妙的。String whereArgs[]
,即我们可以传多个判断因子给它。它是和whereClause语句中的“?”相匹配的。
我们来看下实例:
这是一个自定义的query方法,里面封装了SQLiteDatabase的query方法。我们传我们所要查找的表的列名和判断参数给它(此函数是有点问题的,因为args只能为一个数据,为什么呢?因为我们在whereClause语句中用的是"_id
> ?" ,而如果传入多个数据,则是不合逻辑的。将其修改成如下会更合理点)
但是如果在whereClause语句中有多个判断因子,如:"_id > ? and code = ? "
,则whereArgs 必须为数组 。
另外,我们知道query方法返回的是一个Cursor
对象(指针对象)。所以在做完查寻操作后,我们紧接着就是对Cursor对象的操作。
Cursor对象本身封装了很多有效的方法,如moveToFirst()、isAfterLast()、moveToNext()、getColumnIndexOrThrow(String
columnName)等 。多操作几次Cursor对象的方法就熟练了。
最后我们来看看SQLiteDataBase对象的query()接口:
public Cursor query (String
table, String[]
columns, String
selection, String[]
selectionArgs, String
groupBy, String
having, String
orderBy, String
limit)
Query the given table, returning a
Parameters
table
The table name to compile the query against.
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.
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.
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.
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.
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.
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.
limit
Limits the number of rows returned by the query, formatted as
LIMIT clause. Passing null denotes no LIMIT clause.
Returns
A