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

时间:2011-11-23 19:28:20

标签: java mysql jdbc prepared-statement

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

6 个答案:

答案 0 :(得分:250)

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

答案 1 :(得分:24)

像这样编码:

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

确保不要包含引号' '如下所示,因为它们会导致异常。

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

答案 2 :(得分:4)

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

试试这个。

答案 3 :(得分:1)

Statement stmt = con.createStatement();
String query1 = "";
String query2 = "";

int candidateNo = 42;

query1 = "SELECT * FROM Candidates WHERE CandidateNo = "+ candidateNo;
ResultSet rs = stmt.executeQuery(query1);
//If query can be completed then display name and prompt to continue
if(rs.next()){
    query2 = "SELECT * FROM Achieved WHERE CandidateNo = " + candidateNo;
    ResultSet ts = stmt.executeQuery(query2);
}

答案 4 :(得分:0)

通过使用CONCATE SQL函数,我们可以简化此操作。

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

这很适合我的情况。

答案 5 :(得分:-6)

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


PreparedStatement preparedStatement=con.prepareStatement(query);


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