我正在使用准备好的语句来执行mysql数据库查询。我想实现一个基于关键字的搜索功能。
为此,我需要使用LIKE
关键字,这是我知道的。我以前也使用过预准备语句,但我不知道如何将它与LIKE
一起使用,因为在下面的代码中,我将把'keyword%'
添加到哪里?
我可以在pstmt.setString(1, notes)
中直接使用它作为(1, notes+"%")
或类似的东西吗?我在网上看到了很多关于这个问题的帖子,但到处都没有好的答案。
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
发布于 2011-11-24 03:35:42
您需要在值本身中设置它,而不是在预准备语句SQL字符串中。
因此,这应该适用于前缀匹配:
notes = notes
.replace("!", "!!")
.replace("%", "!%")
.replace("_", "!_")
.replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'");
pstmt.setString(1, notes + "%");
或后缀匹配:
pstmt.setString(1, "%" + notes);
或全局匹配:
pstmt.setString(1, "%" + notes + "%");
发布于 2019-11-21 20:58:14
我们可以使用SQL函数。
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
这对我的情况非常有效。
发布于 2016-03-11 02:01:22
PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');
试试这个。
https://stackoverflow.com/questions/8247970
复制相似问题