Android:带有通配符 (%) 的 SQL rawQuery

发布于 2024-11-05 13:27:44 字数 495 浏览 1 评论 0原文

我有一个 rawQuery() ,其以下 sql 字符串与此类似:

selectionArgs = new String[] { searchString };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);

但现在我必须在搜索中包含通配符,因此我的查询如下所示:

SELECT column FROM table WHERE column LIKE 'searchstring%'

但是当查询包含单引号时,会抛出以下 SQLite 异常: android.database.sqlite.SQLiteException: bind or column index out of range

如何在 a 中运行带有 selectArgs 的 rawQuery带有通配符元素的 SQL 查询?

I'm having a rawQuery() with following sql string similar to this:

selectionArgs = new String[] { searchString };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);

but now I have to include a wildcard in my search, so my query looks something like this:

SELECT column FROM table WHERE column LIKE 'searchstring%'

But when the query contains single quotes the following SQLite Exception is thrown: android.database.sqlite.SQLiteException: bind or column index out of range

How can I run a rawQuery with selectionArgs inside a SQL query with wildcard elements?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酷遇一生 2024-11-12 13:27:44

您必须将%附加到selectionArgs本身:

selectionArgs = new String[] { searchString + "%" };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);

注意:相应地,searchString字符串中的%_仍然用作通配符!

You have to append the % to the selectionArgs itself:

selectionArgs = new String[] { searchString + "%" };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);

Note: Accordingly % and _ in the searchString string still work as wildcards!

心清如水 2024-11-12 13:27:44

Sqlite 框架自动在 ? 两边加上单引号。性格内在。

String [] selectionArgs = {searchString + "%"};
Cursor c;
// Wrap the next line in try-catch
c = db.rawQuery("SELECT column FROM table WHERE like ?", selectionArgs);

就是这样。

The Sqlite framework automatically puts single-quotes around the ? character internally.

String [] selectionArgs = {searchString + "%"};
Cursor c;
// Wrap the next line in try-catch
c = db.rawQuery("SELECT column FROM table WHERE like ?", selectionArgs);

That's it.

南渊 2024-11-12 13:27:44

Brad Hein 和 Mannaz 的解决方案对我不起作用,但它确实有效:

String query = "SELECT column FROM table WHERE column=%s";
String q = String.format(query, "\""+searchString + "%\"");
Cursor c = db.rawQuery(q, null);

Brad Hein's and Mannaz's solution did not work for me, but this did:

String query = "SELECT column FROM table WHERE column=%s";
String q = String.format(query, "\""+searchString + "%\"");
Cursor c = db.rawQuery(q, null);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文