[英]Using "like" wildcard in prepared statement
I am using prepared statements to execute mysql database queries.我正在使用准备好的语句来执行 mysql 数据库查询。 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.为此,我需要使用
LIKE
关键字,我知道的就这么多。 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%'
?而且我之前也使用过准备好的语句,但我不知道如何将它与
LIKE
一起使用,因为从下面的代码中我将在哪里添加'keyword%'
?
Can I directly use it in the pstmt.setString(1, notes)
as (1, notes+"%")
or something like that.我可以直接在
pstmt.setString(1, notes)
中将它用作(1, notes+"%")
或类似的东西。 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();
You need to set it in the value itself, not in the prepared statement SQL string.您需要在值本身中设置它,而不是在准备好的语句 SQL 字符串中。
So, this should do for a prefix-match:因此,这应该用于前缀匹配:
notes = notes
.replace("!", "!!")
.replace("%", "!%")
.replace("_", "!_")
.replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'");
pstmt.setString(1, notes + "%");
or a suffix-match:或后缀匹配:
pstmt.setString(1, "%" + notes);
or a global match:或全局匹配:
pstmt.setString(1, "%" + notes + "%");
Code it like this:像这样编码:
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes + "%");`
Make sure that you DO NOT include the quotes ' ' like below as they will cause an exception.确保您不包括下面的引号'',因为它们会导致异常。
pstmt.setString(1,"'%"+ notes + "%'");
We can use the CONCAT
SQL function.我们可以使用
CONCAT
SQL 函数。
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
This works perfectly for my case.这非常适合我的情况。
PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');
Try this out.试试这个。
String fname = "Sam\u0025";
PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");
ps.setString(1, fname);
String query="select * from test1 where "+selected+" like '%"+SelectedStr+"%';";
PreparedStatement preparedStatement=con.prepareStatement(query);
// where seleced and SelectedStr are String Variables in my program
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.