简体   繁体   English

无法在Java中执行“喜欢”查询

[英]unable to execute “like” query in java

In MYSQL database I have a table name search. 在MYSQL数据库中,我有一个表名搜索。 When I write this query it executed successfully. 当我编写此查询时,它已成功执行。

"select * from 'search' where path like %overview%"

But when I write it in java: 但是当我用Java编写它时:

String query="SELECT path FROM `search` WHERE path like %?% ";
java.sql.PreparedStatement st=con.prepareStatement(query);
st.setString(1,textField.getText() );
ResultSet rs=st.executeQuery();

It's not working and displays an error: 它无法正常工作并显示错误:

com.mysql.jdbc.exception.jdbc4.MySQLSystaxErrorException: you have an error in sql syntax; check the manual that corresponds to your Mysql server version for the right Syntax to use near '%'overview'%' at line 1

String query="SELECT path FROM `search` WHERE path like ? ";
java.sql.PreparedStatement st=con.prepareStatement(query);
st.setString(1,"%"+ textField.getText() + "%" );
ResultSet rs=st.executeQuery();

You can try the above code 您可以尝试上面的代码

The percent signs are literals, if you want to include those in the SQL text, and have MySQL add those to the value you pass in, you could do something like this: 百分号是文字,如果要在SQL文本中包含这些百分号,并让MySQL将这些百分号添加到您传递的值中,则可以执行以下操作:

String query="SELECT path FROM `search` WHERE path LIKE CONCAT('%',?,'%')";

The other alternative is to remove the percent signs from the SQL text statement 另一种选择是从SQL文本语句中删除百分号

String query="SELECT path FROM `search` WHERE path LIKE ?";

and then prepend/append percent characters to the value you supply. 然后在提供的值前/后附加百分号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM