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

    •           Load appropriate JDBC driver class using Class.forName() statement.
    •           Establish a connection using DriverManager.getConnection() statement.

From Java 6 with JDBC 4.0, the first step is no longer needed, as the driver manager attempts to load a suitable 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.Driver class 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:

    • static Connection getConnection(String url) :

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

    • static Connection getConnection(String url, Properties info) :

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

    • static Connection getConnection(String url, String user, String 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.


Recommended Book: Practical Database Programming with Java


Example for JDBC 3.0 and backward

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();
                }
            }
        }
    }
}

 

Examples for JDBC 4.0 and later

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();
                }
            }
        }
    }
}

 

For more information about database URL and JDBC driver download:

Recommended Book: Java Database Best Practices

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