gpt4 book ai didi

java - 在准备好的语句中使用 "like"通配符

转载 作者:行者123 更新时间:2023-12-01 16:25:15 25 4
gpt4 key购买 nike

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

最佳答案

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

关于java - 在准备好的语句中使用 "like"通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62161552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com