首页 文章

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

提问于
浏览
145

我正在使用预准备语句来执行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();

5 回答

  • 23

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

    像这样编码:

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

    请确保 DO NOT 包含引号' ',如下所示,因为它们会导致异常 .

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

    试试吧 .

  • 1
    String fname = "Sam\u0025";
    
    PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");
    
    ps.setString(1, fname);
    
  • -5
    String query="select * from test1 where "+selected+" like '%"+SelectedStr+"%';";
    
    
    PreparedStatement preparedStatement=con.prepareStatement(query);
    
    
    // where seleced and SelectedStr are String Variables in my program
    

相关问题