English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JDBC LIKE Clause

This chapter provides examples of how to select records from a table using a JDBC application. When selecting records from a table, this will add additional conditions using the LIKE clause. Before executing the following example, make sure you have the following conditions:

  • To execute the following example, you can replaceUsernameAndPasswordReplace with actual username and password.

  • Your MySQL or any database you are using has already started and is running.

Necessary steps

To create a new database using a JDBC application, you need to perform the following steps-

  • Import package:It requires you to include the software package that contains the JDBC classes required for database programming. Typically, using import java.sql.* Is enough.

  • Register JDBC driver: It requires you to initialize the driver so that you can open a communication channel with the database.

  • Establish connection:Need to use DriverManager.getConnection() A method to create a Connection object representing a physical connection to the database server.

  • Execute query:An object of the Statement type is needed to construct and submit SQL statements to retrieve records from a table that meets the given conditions. The query usesLIKEThe clause selects records to select all students whose names start with "za".

  • Clean up the environment: All database resources must be explicitly closed, rather than relying on JVM garbage collection.

Example code

Copy and paste the following example into JDBCExample.java, compile and run as follows-

//steps1Import the required software packages
import java.sql.*;
public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //steps2Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");
      //steps3: Establish connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected to database successfully...");
      
      //steps4: Execute query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      // Extract records without condition.
      System.out.println("Fetching records without condition...");
      String sql = "SELECT id, first, last, age FROM Registration";
      ResultSet rs = stmt.executeQuery(sql);
      while(rs.next()){
         //Search by column name
         int id = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");
         //Display value
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
      // Select all IDs equal to or greater than101records
      System.out.println("Fetching records with condition...");
      sql = "SELECT id, first, last, age FROM Registration" +
                   " WHERE first LIKE '%za%' ";
      rs = stmt.executeQuery(sql);
      while(rs.next()){
         //Search by column name
         int id = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");
         //Display value
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
      rs.close();
   }catch(SQLException se){
      //Handle JDBC errors
      se.printStackTrace();
   catch(Exception e){
      //Handling Class.forName error
      e.printStackTrace();
   }finally{
      //Used for closing resources
      try{
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){
      }// Nothing to do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }
   System.out.println("Goodbye!");
}//End of main
}//End of JDBCExample

Now, let's compile the above example as follows:

C:\>javac JDBCExample.java
C:\>

RuntimeJDBCExampleIt will produce the following result-

C:\>java JDBCExample
Connecting to a selected database...
Database connected successfully...
Creating statement...
Fetching records without condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Fetching records with condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
Goodbye!
C:\>