使用“喜欢”在准备声明中的通配符
我正在使用准备好的语句执行MySQL数据库查询。我想根据各种关键字来实现搜索功能。
为此,我需要使用关键字,这是我所知道的。而且我之前还曾使用过准备的语句,但是我不知道如何使用喜欢
,因为从以下代码中我在哪里添加'keyword%'
?
我可以在pstmt.setstring(1,notes)
as (1,注释+“%”)
或类似的东西中直接使用它。我在网上看到了很多帖子,但任何地方都没有好的答案。
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
I am using prepared statements to execute mysql database queries. And I want to implement a search functionality based on a keyword of sorts.
For that I need to use LIKE
keyword, that much I know. And I have also used prepared statements before, but I do not know how to use it with LIKE
because from the following code where would I add the 'keyword%'
?
Can I directly use it in the pstmt.setString(1, notes)
as (1, notes+"%")
or something like that. I see a lot of posts on this on the web but no good answer anywhere.
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要将其设置在值本身中,而不是在准备好的语句SQL字符串中。
因此,这应该对前缀匹配:
或后缀匹配:
或全局匹配:
You need to set it in the value itself, not in the prepared statement SQL string.
So, this should do for a prefix-match:
or a suffix-match:
or a global match:
我们可以使用
concat
sql函数。这对我的情况非常有用。
We can use the
CONCAT
SQL function.This works perfectly for my case.
像这样的代码:
确保您不包含引号',因为它们会导致例外。
Code it like this:
Make sure that you DO NOT include the quotes ' ' like below as they will cause an exception.
尝试一下。
Try this out.