我使用准备语句执行mysql数据库查询。我想实现一个基于关键字的搜索功能。
为此,我需要使用LIKE关键字,我知道这么多。我以前也使用过准备好的语句,但我不知道如何使用LIKE,因为从下面的代码中,我将在哪里添加'关键字%'?
我可以直接在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();
您需要在值本身中设置它,而不是在准备好的语句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 + "%");
您需要在值本身中设置它,而不是在准备好的语句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 + "%");