How to use quotes correctly while using LIKE with search variable in MySQL in Java?

MySQLMySQLi DatabaseJava

Following is the correct syntax to use LIKE with search variable −

String sqlQuery;
sqlQuery = "select *from yourTableName where yourColumnName like '%" +yourSearchVariableName + "%'";

Let us create a table −

mysql> create table demo19
−> (
−> id int not null auto_increment primary key,
−> name varchar(50)
−> );
Query OK, 0 rows affected (3.48 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo19(name) values('John Smith');
Query OK, 1 row affected (0.15 sec)

mysql> insert into demo19(name) values('David Miller');
Query OK, 1 row affected (0.15 sec)

mysql> insert into demo19(name) values('Adam Smith');
Query OK, 1 row affected (0.12 sec)

mysql> insert into demo19(name) values('Chris Brown');
Query OK, 1 row affected (0.13 sec)

Display records from the table using select statement −

mysql> select *from demo19

This will produce the following output −

+----+--------------+
| id | name         |
+----+--------------+
|  1 | John Smith   |
|  2 | David Miller |
|  3 | Adam Smith   |
|  4 | Chris Brown  |
+----+--------------+
4 rows in set (0.00 sec)

Example

Following is the Java code to use quotes correctly while using LIKE with search variable −

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RemoveJavaQueryError {
   public static void main(String[] args) {
      Connection con = null;
      Statement statement = null;
      try {
         String searchKeyWord = "Smith";
         Class.forName("com.mysql.jdbc.Driver");
         con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sampledatabase", "root", "123456");
         statement = (Statement) con.createStatement();
         String sqlQuery;
         sqlQuery = "select *from demo19 where name like '%" + searchKeyWord + "%'";
         ResultSet rs = statement.executeQuery(sqlQuery);
         while (rs.next()) {
            System.out.println(rs.getString("name"));
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

This will produce the following output −

John Smith
Adam Smith

Following is the snapshot of sample output.

raja
Published on 19-Nov-2020 11:31:49
Advertisements