设为首页 加入收藏

TOP

Android 中数据库查询方法 query() 中的 select
2014-11-24 03:29:36 来源: 作者: 【 】 浏览:0
Tags:Android 数据库 查询 方法 query select

view plaincopy to clipboardprint
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)


selection 参数很好理解,就是 SQL 语句中 WHERE 后面的部分,即过滤条件, 比如可以为 id=3 AND name='Kevin Yuan' 表示只返回满足 id 为 3 且 name 为 "Kevin Yuan" 的记录。


再实际项目中像上面那样简单的“静态”的 selection 并不多见,更多的情况下要在运行时动态生成这个字符串,比如


view plaincopy to clipboardprint
public doQuery(long id, final String name) {
mDb.query("some_table", // table name
null, // columns
"id=" + id + " AND name='" + name + "'", // selection
//...... 更多参数省略
);
}
public doQuery(long id, final String name) {
mDb.query("some_table", // table name
null, // columns
"id=" + id + " AND name='" + name + "'", // selection
//...... 更多参数省略
);
}


在这种情况下就要考虑一个字符转义的问题,比如如果在上面代码中传进来的 name 参数的内容里面有单引号('),就会引发一个 "SQLiteException syntax error .... "。


手工处理转义的话,也不麻烦,就是 String.replace() 调用而已。但是 Android SDK 为我们准备了 selectionArgs 来专门处理这种问题:


view plaincopy to clipboardprint
public void doQuery(long id, final String name) {
mDb.query("some_table", // table name
null, // columns
"id=" + id + " AND name= ", // selection
new String[] {name}, //selectionArgs
//...... 更多参数省略
);
// ...... 更多代码
}
public void doQuery(long id, final String name) {
mDb.query("some_table", // table name
null, // columns
"id=" + id + " AND name= ", // selection
new String[] {name}, //selectionArgs
//...... 更多参数省略
);
// ...... 更多代码
}


也就是说我们在 selection 中需要嵌入字符串的地方用 代替,然后在 selectionArgs 中依次提供各个用于替换的值就可以了。在 query() 执行时会对 selectionArgs 中的字符串正确转义并替换到对应的 处以构成完整的 selection 字符串。 有点像 String.format()。


不过需要注意的是 并不是“万金油”,只能用在原本应该是字符串出现的地方。比如下面的用法是错误的:


view plaincopy to clipboardprint
public void doQuery(long id, final String name) {
mDb.query("some_table", // table name
null, // columns
" = " + id + " AND name= ", // selection XXXX 错误! 不能用来替换字段名
new String[]{"id", name}, //selectionArgs
//...... 更多参数省略
);
// ...... 更多代码
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android基础教程:利用NDK编写Hel.. 下一篇mini2440 成功移植 qt embedded l..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C++中智能指针的性能 (2025-12-25 03:49:29)
·如何用智能指针实现c (2025-12-25 03:49:27)
·如何在 C 语言中管理 (2025-12-25 03:20:14)
·C语言和内存管理有什 (2025-12-25 03:20:11)
·为什么C语言从不被淘 (2025-12-25 03:20:08)