Jdbc Connect To MySQL

Here we show an example of how to connect to A MySQL database using JDBC. To work along with this example you will need to download the MySQL driver.

Alternatively you can use Maven to include the MySQL driver.

1
2
3
4
5
<dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>5.1.35</version>
</dependency>

Load MySQL JDBC Driver

The first step is to load the MySQL JDBC driver as shown in the below example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public void loadDriver() {
        System.out.println("Looking for MySQL Driver on classpath.");

        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("MySQL JDBC Driver Loaded");
        } catch (ClassNotFoundException e) {
            System.out
                    .println("No MySQL driver found on classpath.  Please add MySql Driver to classpath.");
            throw new RuntimeException(e);
        }
}

Connect To MySQL

Once the driver is loaded the next step is to connect to MySQL via the loaded driver.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public void connect(final String userName, final String password) {

        try {
            System.out
                    .println(String
                            .format("Attempting to connect to MySql Database with user: %s and password: %s ",
                                    userName, password));

            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/javaCore", userName, password);

        } catch (SQLException e) {
            System.out
                    .println("Error unable to connect. Check console stack trace.");
            throw new RuntimeException(e);
        }
}

JDBC Connection Cleanup

Once finished with the connection it is important to close it to free the allocated resources.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public static void main(String[] args) {
        MySqlConnectionExample example = new MySqlConnectionExample();

        try {
            example.loadDriver();
            example.connect("root", "root");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            example.closeConnection();
        }
}

JDBC MySQL Connection Example Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.stephenenright.tutorials.javajdbc.connection;

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

public class MySqlConnectionExample {

    private Connection connection = null;

    public void loadDriver() {
        System.out.println("Looking for MySQL Driver on classpath.");

        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("MySQL JDBC Driver Loaded");
        } catch (ClassNotFoundException e) {
            System.out
                    .println("No MySQL driver found on classpath.  Please add MySql Driver to classpath.");
            throw new RuntimeException(e);
        }
    }

    public void connect(final String userName, final String password) {

        try {
            System.out
                    .println(String
                            .format("Attempting to connect to MySql Database with user: %s and password: %s ",
                                    userName, password));

            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/javaCore", userName, password);

        } catch (SQLException e) {
            System.out
                    .println("Error unable to connect. Check console stack trace.");
            throw new RuntimeException(e);
        }
    }

    public void closeConnection() {
        if (connection != null) {
            System.out.println("Connection to database successful.");

        } else {
            System.out.println("Failed to connect to database");
        }

        try {
            connection.close();
        } catch (Exception e) {
            System.err.println("Warning connection not closed");
        }
    }

    public Connection getConnection() {
        return connection;
    }

    public static void main(String[] args) {
        MySqlConnectionExample example = new MySqlConnectionExample();

        try {
            example.loadDriver();
            example.connect("root", "root");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            example.closeConnection();
        }
    }
}

Run The Example

The example can be executed from the IDE of your choosing. To run from the command line you can use a similar command to that shown below:

1
java -cp ${PATH_TO_JAR}/Oracle-connector-java-5.1.8-bin.jar;${PATH_TO_CLASSES_DIR}  com.github.senrightlearn.java.jdbc.connection.MySqlConnectionExample

Code Output

1
2
3
4
Looking for MySQL Driver on classpath.
MySQL JDBC Driver Loaded
Attempting to connect to MySql Database with user: root and password: password
Connection to database successful.

Conclusion

In this tutorial we looked at how to connect to oracle using MySQL, we also looked at the main steps when working with MySQL with JDBC, such as, loading the driver, connecting to MySQL, and cleaning up the connection when we are finished.