JDBC - Connecting to the MySQL database example

Posted on January 21, 2017


Technologies used:   JDK 1.8.0_121 | MySQL 5.7.12 | Eclipse Mars.2 (4.5.2)

In this post, we will learn how to connect the MySQL database via JDBC API. There are five steps for connecting to the MySQL database.

  • Load and register the JDBC driver (Class.forName() is not needed since JDBC 4.0) 
  • Open connection to the database
  • Create a statement object to perform a query.
  • Execute the statement object and return a query resultset.
  • Close connection to the database

JAR dependencies

Download the MySQL JDBC driver from https://dev.mysql.com/downloads/connector/j/ and add to build path of your project.

Java Program

Here is an example to demonstrate the above steps.

JDBCMySQLExample.java

package com.boraji.tutorial.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author imssbora
 */
public class JDBCMySQLExample {
  public static void main(String[] args) {

    String jdbcUrl = "jdbc:mysql://localhost:3306/BORAJI";
    String username = "root";
    String password = "admin";

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

    try {
      // Step 1 - Load driver
      // Class.forName("com.mysql.cj.jdbc.Driver"); //Class.forName() is not needed since JDBC 4.0

      // Step 2 - Open connection
      conn = DriverManager.getConnection(jdbcUrl, username, password);

      // Step 3 - Execute statement
      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT version()");

      // Step 4 - Get result
      if (rs.next()) {
        System.out.println(rs.getString(1));
      }

    } catch (SQLException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {

        // Step 5 Close connection
        if (stmt != null) {
          stmt.close();
        }
        if (rs != null) {
          rs.close();
        }
        if (conn != null) {
          conn.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

  }
}

Output

5.7.12-log