Write JDBC steps to connect to MySQL database in Java

In order to connect to MySQL database, Follow below steps

  1. Load JDBC Driver
  2. Create Connection object (By passing url, username and password)
  3. Create statement object (from Connection object)
  4. Execute query (from Statement object)
  5. Close connection
import java.sql.*;  
  
public class MySqlConnection {  
    public static void main(String args[]) {  
        try {  
            // Step-1: Load JDBC Driver class  
            Class.forName("com.mysql.jdbc.Driver");  
              
            // Step-2: Create Connection object  
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase", "root", "admin");  
              
            // Step-3: Create Statement object (Statement, PreparedStatement or CallableStatement)  
            Statement stmt = con.createStatement();  
              
            // Step-4: Execute query (In case of PreparedStatement or CallableStatement use executeUpdate method)  
            ResultSet rs = stmt.executeQuery("select * from emp");  
              
            // Process resultset  
            while (rs.next())  
                System.out.println(rs.getInt(1) + "  " + rs.getString(2) + "  " + rs.getString(3));  
              
            //Step-5: Close connection  
            con.close();  
        } catch (Exception e) {  
            // Handle Exception here
        }  
    }  
}

Class.forName(String arg) is a static method of Class which is used to load classes using reflection.

DriverManager is a basic service for managing a set of JDBC drivers.

Statement is the factory for resultset. It is used for general purpose access to the database. It executes a static SQL query at runtime.

PreparedStatement is used when we need to provide input parameters to the query at runtime.

CallableStatement is used when we need to access the database stored procedures. It can also accept runtime parameters.

Author: Mahesh

Technical Lead with 10 plus years of experience in developing web applications using Java/J2EE and web technologies. Strong in design and integration problem solving skills. Ability to learn, unlearn and relearn with strong written and verbal communications.