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?
The SQL LIKE OperatorThe LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.
like("digital","%cam%"); myComparator. like("digital","tal%");
STRCMP() function in MySQL is used to compare two strings. If both of the strings are same then it returns 0, if the first argument is smaller than the second according to the defined order it returns -1 and it returns 1 when the second one is smaller the first one.
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();
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With