In this JDBC tutorial, you will learn how to write Java code to establish connection to a relational database.

In order to make a connection to a specific database system, it requires doing the following 2 steps:

From Java 6 with JDBC 4.0, the first step is no longer needed, as the driver manager attempts to load a suitable JDBC driver from classpath. That means, if you placed a JAR file of JDBC driver for MySQL such as mysql-connector-java-5.1.7-bin.jar in the classpath, the driver manager will automatically load the com.mysql.jdbc.Driverclass which it found in the JAR file.

The DriverManager class is available from package java.sql. There are three versions of getConnection() method which allow us to establish a connection to a database in three different ways:

Establishes a connection from the given database URL in the form of: jdbc:subprotocol:subname

Establishes a connection from the given database URL and a Properties object which includes additional information such as user and password.

Establishes a connection from the given database URL, user and password.        

As you notice, all methods require a database URL which is a string in a special format that contains information about the database to connect to, such as server name, database name, user, password… Database URL is specific to a particular database system. Following is an example of a database URL for MySQL:

jdbc:mysql://localhost:3306/test

where localhost is server name, 3306 is port number, and test is database name.

All the methods return a Connection object which is used for making SQL queries to the connected database.

The following code examples illustrate establishing connection to a MySQL database. Follow this tutorial to download JDBC driver for MySQL.

 

1. Java Connect to Database Example with JDBC 3.0 or older



It requires to load the JDBC driver explicitly using Class.forName() method:

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

public class ConnectJDBC3 {
    public static void main(String[] args) {
        String databaseURL = "jdbc:mysql://localhost:3306/test";
        String user = "user";
        String password = "password";
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(databaseURL, user, password);
            if (conn != null) {
                System.out.println("Connected to the database");
            }
        } catch (ClassNotFoundException ex) {
            System.out.println("Could not find database driver class");
            ex.printStackTrace();
        } catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
 

2. Java Connect to Database Example with JDBC 4.0 or newer

From JDBC 4.0 (Java 6), we can safely remove the Class.forName() statement. Following are three examples of connection to the same database in three different ways.

Example 1: getConnection(String url)

In this way, we must pass the user and password directly into the database URL:

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

public class DBConnect1 {
    public static void main(String[] args) {
        String databaseURL = "jdbc:mysql://localhost:3306/test?user=root&password=root123";
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(databaseURL);
            if (conn != null) {
                System.out.println("Connected to the database");
            }
        } catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
 

Example 2: getConnection(String url, Properties info) :

In this way, we put the user and password in a Properties object:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBConnect2 {
    public static void main(String[] args) {
        String databaseURL = "jdbc:mysql://localhost:3306/test";
        Connection conn = null;
        try {
            Properties props = new Properties();
            props.put("user", "root");
            props.put("password", "root123");
            conn = DriverManager.getConnection(databaseURL, props);
            if (conn != null) {
                System.out.println("Connected to the database");
            }
        } catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
 

Example 3: getConnection(String url, String user, String password)

In this way, we supply the user and password directly into the method’s arguments:

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

public class DBConnect3 {
    public static void main(String[] args) {
        String databaseURL = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "root123";
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(databaseURL, user, password);
            if (conn != null) {
                System.out.println("Connected to the database");
            }
        } catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
 

NOTE: Since Java 1.7, you can use the try-with-resources statement to make connection to database without explicitly closing the connection, for example:

public void connectDatabase(String url, String user, String password) {
 
    try (Connection conn = DriverManager.getConnection(url, user, password)) {
 
        if (conn != null) {
            System.out.println("Connected to the database");
        }
    } catch (SQLException ex) {
        System.out.println("An error occurred. Maybe user/password is invalid");
        ex.printStackTrace();
    }
}
The try-with-resources statement automatically close the resource (database connection) for you.

That's some Java code examples for connecting to a database with JDBC.

 

JDBC API References:

 

Connect to a specific database Tutorials:

 

Other JDBC Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (ConnectJDBC3.java)ConnectJDBC3.java[JDBC 3.0 example]0.9 kB
Download this file (DBConnect1.java)DBConnect1.java[Example 1]0.6 kB
Download this file (DBConnect2.java)DBConnect2.java[Example 2]0.8 kB
Download this file (DBConnect3.java)DBConnect3.java[Example 3]0.7 kB