在准备好的声明中使用"like"通配符

ssn*_*ssn 159 java mysql jdbc prepared-statement

我正在使用预准备语句来执行mysql数据库查询.我想基于各种关键字实现搜索功能.

为此我需要使用LIKE关键字,我知道的很多.我之前也使用过预处理语句,但我不知道如何使用它,LIKE因为从下面的代码我将添加'keyword%'

我可以直接在pstmt.setString(1, notes)as (1, notes+"%")或类似的东西中使用它.我在网上看到很多帖子,但在任何地方都没有好的答案.

PreparedStatement pstmt = con.prepareStatement(
      "SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 260

您需要在值本身中设置它,而不是在预准备语句SQL字符串中设置它.

所以,这应该用于前缀匹配:

notes = notes
    .replace("!", "!!")
    .replace("%", "!%")
    .replace("_", "!_")
    .replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
        "SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'");
pstmt.setString(1, notes + "%");
Run Code Online (Sandbox Code Playgroud)

或后缀匹配:

pstmt.setString(1, "%" + notes);
Run Code Online (Sandbox Code Playgroud)

或全球匹配:

pstmt.setString(1, "%" + notes + "%");
Run Code Online (Sandbox Code Playgroud)

  • +1 OP可以在SQL中"设置"它 - 就像`... LIKE'%'|| ?|| '%'或类似 - 但这不太灵活. (17认同)
  • 当使用`pstmt.setString(2,“%” + notes +“%”)时,不区分大小写的仍然可以使用`WHERE UPPER(?)LIKE UPPER(?)`。 (2认同)
  • @BalusC这适用于我的测试中的MSSQL,Postgres和MySQL.作为参数的字符串本身被解释为数据和控制指令的混合.SQL连接在解释之前发生并保留漏洞.IEEE安全设计中心称[严格区分数据和控制指令,绝不处理从不受信任来源收到的控制指令](http://cybersecurity.ieee.org/2015/11/13/strictly-separatedata-and-control -instructions和 - 永不过程控制的指令接收的从 - 不可信来源/). (2认同)

小智 26

像这样编码:

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

请确保您不要包含下面的引号,因为它们会导致异常.

pstmt.setString(1,"'%"+ notes + "%'");
Run Code Online (Sandbox Code Playgroud)

  • 虽然听起来好像不会有人遇到这个假设,但它实际上非常有效,尤其是在使用 Oracle 时。感谢您指出! (2认同)

小智 12

我们可以使用CONCATSQL 函数。

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

这非常适合我的情况。

  • `.. 注释如 '%' || ?|| '%'` 也有效 (2认同)

小智 6

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

试试这个。