How do I create a connection to database?

This post is about an example for obtaining a connection to MySQL database. For connecting to other database all you have to do is change the url to match to url format for a particular database and of course you have to register a correct JDBC driver of the database you are using.

Here are the steps:

  • Define the JDBC url of your database. Below is the format of JDBC url for MySQL database.
public static final String URL = "jdbc:mysql://localhost/kodejava";
  • Define the username dan password for the connection.
public static final String USERNAME = "kodejava";
public static final String PASSWORD = "kodejava123";
  • Register the database JDBC driver to be used by our program. Below is the driver for MySQL database.
Class.forName("com.mysql.jdbc.Driver");
  • We can open a connection to the database.
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
  • Do any database operation such as select, insert, update and delete.
  • Finally don’t forget to close the Connection object. We usually do this in the finally block of the try-catch block.
if (connection != null) {
    connection.close();
}

Here is the complete code snippet.

package org.kodejava.example.sql;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionSample {
    public static final String URL = "jdbc:mysql://localhost/kodejava";
    public static final String USERNAME = "kodejava";
    public static final String PASSWORD = "kodejava123";

    public static void main(String[] args) throws Exception {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }
}