Android 中涉及数据库查询的地方一般都会有一个 query() 方法,而这些 query 中有大都
( 全 部 ? ) 会 有 一 个 参 数 seleconArgs , 比 如 下 面 这 个
android.database.sqlite.SQLiteDatabase.query():
view plaincopy to clipboardprint?
public Cursor query (String table, String[] columns, String selecon, String[] seleconArgs, String
groupBy, String having, String orderBy)
public Cursor query (String table, String[] columns, String selecon, String[] seleconArgs, String
groupBy, String having, String orderBy)
selecon 参数很好理解,就是 SQL 语句中 WHERE 后面的部分,即过滤条件, 比如可以为
id=3 AND name='Kevin Yuan' 表示只返回满足 id 为 3 且 name 为 "Kevin Yuan" 的记录。
再实际项目中像上面那样简单的“静态”的 selecon 并不多见,更多的情况下要在运行时
动态生成这个字符串,比如
view plaincopy to clipboardprint?
public doQuery(long id, 2nal String name) {
mDb.query("some_table", // table name
null, // columns
"id=" + id + " AND name='" + name + "'", // selecon
//...... 更多参数省略
);
}
public doQuery(long id, 2nal String name) {
mDb.query("some_table", // table name
null, // columns
"id=" + id + " AND name='" + name + "'", // selecon
//...... 更多参数省略
);
}
在这种情况下就要考虑一个字符转义的问题,比如如果在上面代码中传进来的 name 参数
的内容里面有单引号('),就会引发一个 "SQLiteExcepon syntax error .... "。
手工处理转义的话,也不麻烦,就是 String.replace() 调用而已。但是 Android SDK 为我们
准备了 seleconArgs 来专门处理这种问题:
view plaincopy to clipboardprint?
public void doQuery(long id, 2nal String name) {
mDb.query("some_table", // table name
null, // columns
"id=" + id + " AND name=?", // selecon
new String[] {name}, //seleconArgs
评论0
最新资源