Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MySQL like operator in JDBC?

Tags:

java

mysql

jdbc

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?

like image 325
Sheeyla Avatar asked Jul 06 '11 16:07

Sheeyla


People also ask

How use like in SQL query in Java?

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.

How do you write a like statement in Java?

like("digital","%cam%"); myComparator. like("digital","tal%");

How do I match a string in MySQL?

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.


1 Answers

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();
// ...
like image 194
BalusC Avatar answered Oct 06 '22 17:10

BalusC