gpt4 book ai didi

android - ContentResolver.query(...) 中的 selectionArgs 可以是子查询吗?

转载 作者:IT王子 更新时间:2023-10-29 06:27:25 33 4
gpt4 key购买 nike

我在 Android 上使用 SQLite。
我使用 ContentProvider 从数据库中查询数据。现在,当我尝试通过 ContentResolver

使用子查询时遇到问题
String selection = "cat_id NOT IN ?"
String[] selectionArgs = new String[]{"(SELECT Categories.id FROM Categories)"}
cursor = mResolver.query(getContentUri(), getListColumns(),
selection, selectionArgs, orderBy);

这是错误:

08-06 10:32:36.070: E/AndroidRuntime(2151): Caused by: android.database.sqlite.SQLiteException: near "?": syntax error (code 1): , while compiling: SELECT * FROM TRANSACTIONS WHERE cat_id NOT IN ? ORDER BY time_created ASC, id ASC`

我的问题是“我可以将 selectionArgs 用作子查询吗?”
我的目的是“获取 cat_id 不在类别表中的事务列表”。
谁能帮帮我?

最佳答案

别忘了这里吗?实际上是一个值的占位符。稍后由android绑定(bind)。

因此,您不会将查询替换为 ?。作为使用点?是保证sql代码不被用户参数注入(inject)。

String selection = "cat_id NOT IN ?"
String[] selectionArgs = new String[]{"(SELECT Categories.id FROM Categories)"}
cursor = mResolver.query(getContentUri(), getListColumns(), selection, selectionArgs, orderBy);

等同于你写类似的东西

String selection = "cat_id NOT IN '(SELECT Categories.id FROM Categories)'"

你想要运行的查询实际上被认为是一个值,这意味着NOT IN '(some value)' 不是有效的 sql。

我建议您只删除 ?并将其替换为您在 where 参数中的查询,这将修复它。

您会使用 ?像这样的占位符(如果你知道它不必在什么地方)。

String selection = "cat_id NOT IN (?, ?)"
String[] selectionArgs = new String[]{"value1", "value2"}
cursor = mResolver.query(getContentUri(), getListColumns(), selection, selectionArgs, orderBy);

编辑:尝试

String selection = "cat_id NOT IN (SELECT Categories.id FROM Categories)"
cursor = mResolver.query(getContentUri(), getListColumns(), selection, null, orderBy);

关于android - ContentResolver.query(...) 中的 selectionArgs 可以是子查询吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18070513/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com