在准备好的语句中使用“ like”通配符


176

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

Answers:


281

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

18
+1 OP可以通过... LIKE '%' || ? || '%'或类似方式在SQL中“设置”它,但是灵活性较差。
— pilcrow,

我如何在非区分大小写模式下执行此操作?:)
— Alpha Gabriel V. Timbol 2015年

2
使用WHERE UPPER(?) LIKE UPPER(?)时不区分大小写仍可以使用pstmt.setString(2, "%" + notes + "%")
— Zig 2015年

1
@Alain:谢谢。只是想知道,这是否适用于全世界都知道的所有RDBMS?也许'%' || ? || '%'在第一个评论提到为好,毕竟?我现在没有机会进行实验。
— BalusC 2015年

2
@BalusC在我的测试中适用于MSSQL,Postgres和MySQL。成为参数的字符串本身被解释为数据和控制指令的混合。SQL串联会在解释并保留漏洞之前发生。IEEE安全设计中心表示要严格分开数据和控制指令,并且切勿处理从不可信来源收到的控制指令。
— 阿兰·奥德亚

28

像这样编码:

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

确保不要像下面那样包含引号'',因为它们会引起异常。

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

1
尽管听起来好像不会有人遇到这个假设,但实际上这是非常有效的,尤其是在使用Oracle时。感谢您指出!
— asg 2015年

5

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

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

这对于我的情况来说是完美的。


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

试试看



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


PreparedStatement preparedStatement=con.prepareStatement(query);


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

这是不安全的,请使用参数化的preparedstatement。
— Durgesh Kumar
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.