Bright Java Tutorial

is brought to you by DoITBright LLC

Java

JDBC Connect Java To MySQL Database

It is very common that we will need to connect our Java application to a Relational Database Management System or RDBMS. A popular database that is also offered as community license is MySQL. Therefore, a Java and MySQL combination is very common. It is assumed in this tutorial that you have a prior knowledge of MySQL. Here are the things we will need to do before we start writing our Java code...

Let us now write our application.

  package com.example.core.jdbc;

  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.SQLException;
  import java.sql.Statement;
  import java.text.SimpleDateFormat;
  import java.util.Date;

  public class ConnectJavaToMySql {

    public static void main(String args[]) {
      Connection connection = null;
	  Statement statement = null;
	  try {
	    Class.forName("com.mysql.jdbc.Driver");
	    connection = DriverManager.getConnection(
	      "jdbc:mysql://localhost:3306/MY_FIRST_DB?" + 
		  "user=root&password=root");
	    statement = connection.createStatement();
	    String email = "customer01@testmail.com";
	    Date now = new Date();
	    SimpleDateFormat sdf 
	      = new SimpleDateFormat("yyyy-MM-dd");
	    String strNow = sdf.format(now);
	    String sql 
	      = "INSERT INTO ACCOUNT(EMAIL,CREATE_DATE)" 
	      + " VALUES ('" + email + "', '" + strNow + "')";
	    statement.executeUpdate(sql);
	  } catch(SQLException sqle) {
        System.out.println(sqle.getMessage());
	  } catch(Exception e) {
        System.out.println(e.getMessage());
	  } finally {
        try {
          statement.close();
          connection.close();
        } catch (Exception e) {
          System.out.println(e.getMessage());
        }
	  }
    }
  }
                            


In our example, it is assumed that our MySQL user name 'root' has a corresponding password of 'root'. The first 3 statements inside the try block initializes the MySQL driver, creates the connection object and creates the statement object. The succeeding few lines of codes is trying to construct an SQL INSERT statement using a Java String concatenation. The last line of code inside the try block executes the SQL INSERT statement. Do not forget to always close the statement and connection object. It will cause memory leak if you forget to close especially the connection object. In this example, these things happens at the finally block. We placed the closing of connection at the finally block because finally block always gets executed in a try-catch-catch-finally.

In this lesson, we have learned how to connect our Java application to a MySQL database.


Back