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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5934854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:31:57  来源:igfitidea点击:

Android: SQL rawQuery with wildcard (%)

javaandroidsqlite

提问by whlk

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

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

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%'

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

但是当查询包含单引号时,会抛出以下 SQLite 异常: 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?

如何在带有通配符元素的 SQL 查询中使用 selectionArgs 运行 rawQuery?

回答by whlk

You have to append the %to the selectionArgs itself:

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

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

Note: Accordingly %and _in the searchStringstring still work as wildcards!

注意:因此%_searchString字符串中仍然可以作为通配符使用!

回答by Brad Hein

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

Sqlite 框架会自动在 ? 性格内向。

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.

而已。

回答by Solata

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

Brad Hein 和 Mannaz 的解决方案对我不起作用,但这样做了:

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