您的位置:首页 > 数据库 > SQL

How to use MySQL like operator in JDBC?

2014-04-05 23:00 393 查看
I have the following syntax in my code, but it is not working when I am trying to use the
LIKE
operator
in JDBC. It works fine in this way, when it is just equal:

ResultSet resultSet = statement.executeQuery("SELECT * FROM drawings WHERE name = '"+ DT +"'");


But if I want to use the
LIKE
operator
to search as a wildcard, I keep getting the error saying that "%" is not a valid character. How I can correctly use the LIKE operator?

From
the comments:

query=("SELECT * FROM drawings WHERE name LIKE '"%DT%"'");


This does not compile. Assuming that
DT
is
a variable, then it should rather look like

query = "SELECT * FROM drawings WHERE name LIKE '%" + DT + "%'";


(pay attention to the syntax highlighting, the
%
has
to be part of the SQL string!)

However, concatenating user-controlled string variables like that in a SQL query puts doors wide open for successful SQL
injection attacks. Learn how
to use
PreparedStatement
and
use it instead.
String sql = "SELECT * FROM drawings WHERE name LIKE ?";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "%" + DT + "%");
resultSet = preparedStatement.executeQuery();
// ...


from
StackOverFlow

End
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: