java—在prepared语句中使用“like”通配符

bvuwiixz  于 2021-07-26  发布在  Java
关注(0)|答案(6)|浏览(390)

我使用prepared语句执行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();
wlzqhblo

wlzqhblo1#

您需要在值本身中设置它,而不是在准备好的语句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 + "%");
6tdlim6h

6tdlim6h2#

编码如下:

PreparedStatement pstmt = con.prepareStatement(
    "SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes + "%");`

请确保不要包含下面这样的引号“”,因为它们会导致异常。

pstmt.setString(1,"'%"+ notes + "%'");
2eafrhcq

2eafrhcq3#

我们可以使用 CONCAT sql函数。

PreparedStatement pstmt = con.prepareStatement(
      "SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();

这对我的案子很有效。

a7qyws3x

a7qyws3x4#

PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');

试试这个。

oo7oh9g9

oo7oh9g95#

String fname = "Sam\u0025";

PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");

ps.setString(1, fname);
m528fe3b

m528fe3b6#

String query="select * from test1 where "+selected+" like '%"+SelectedStr+"%';";

PreparedStatement preparedStatement=con.prepareStatement(query);

// where seleced and SelectedStr are String Variables in my program

相关问题