How to use MySQL as a statement in JDBC?

I have the following syntax in my code, but it does not work when I try to use a statement LIKEin JDBC. It works fine in this case when it is equal to:

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

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

+5
source share
1 answer

From the comments:

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

This does not compile. Assuming what DTis a variable, then it should look like

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

( , % SQL!)

, , SQL-, SQL . , PreparedStatement .

String sql = "SELECT * FROM drawings WHERE name LIKE ?";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "%" + DT + "%");
resultSet = preparedStatement.executeQuery();
// ...
+15

All Articles