我是sqlite和数据库的新手。我有一个Set输入。当我记录它时,它看起来像这样:
D/tag input: [item1,item2,item3,item4]
现在我想查询数据库中的这些项目。但我从中一无所获。这是我的问题:
cursor = db.rawQuery("SELECT * from menu_items where menu_item_name=?", new String[]{input})
我不知道我哪里做错了。有人能帮我处理这个案子吗?感谢
由于input
是一个包含逗号分隔字符串列表的字符串,因此不能使用运算符=
或IN
您需要的是操作员LIKE
如果input
的值中也有方括号:
cursor = db.rawQuery(
"SELECT * FROM menu_items WHERE ',' || REPLACE(REPLACE(?, '[', ''), ']', '') || ',' LIKE '%,' || menu_item_name || ',%'",
new String[]{input}
);
如果没有,则可以简化代码:
cursor = db.rawQuery(
"SELECT * FROM menu_items WHERE ',' || ? || ',' LIKE '%,' || menu_item_name || ',%'",
new String[]{input}
);
如果每个逗号后面都有空格:
cursor = db.rawQuery(
"SELECT * FROM menu_items WHERE ', ' || ? || ', ' LIKE '%, ' || menu_item_name || ', %'",
new String[]{input}
);
您应该使用IN,类似
cursor = db.rawQuery("SELECT * from menu_items where menu_item_name in " +
"(" + Arrays.stream(input).map(e-> "'" + e + "'").collect(Collectors.joining(",")) + ")"
)