ssn*_*ssn 159 java mysql jdbc prepared-statement
我正在使用预准备语句来执行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();
Run Code Online (Sandbox Code Playgroud)
Bal*_*usC 260
您需要在值本身中设置它,而不是在预准备语句SQL字符串中设置它.
所以,这应该用于前缀匹配:
notes = notes
.replace("!", "!!")
.replace("%", "!%")
.replace("_", "!_")
.replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'");
pstmt.setString(1, notes + "%");
Run Code Online (Sandbox Code Playgroud)
或后缀匹配:
pstmt.setString(1, "%" + notes);
Run Code Online (Sandbox Code Playgroud)
或全球匹配:
pstmt.setString(1, "%" + notes + "%");
Run Code Online (Sandbox Code Playgroud)
小智 26
像这样编码:
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes + "%");`
Run Code Online (Sandbox Code Playgroud)
请确保您不要包含下面的引号,因为它们会导致异常.
pstmt.setString(1,"'%"+ notes + "%'");
Run Code Online (Sandbox Code Playgroud)
小智 12
我们可以使用CONCAT
SQL 函数。
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
Run Code Online (Sandbox Code Playgroud)
这非常适合我的情况。
小智 6
PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');
Run Code Online (Sandbox Code Playgroud)
试试这个。
归档时间: |
|
查看次数: |
155798 次 |
最近记录: |