This article explains how to write Java code to connect to a MySQL database server, step by step. If you just want to see the code example, click on Code example: a simple program connects to MySQL. If you have never written Java code to connect MySQL before, it’s worth reading this tutorial from the beginning.

Table of content:

1. Download JDBC driver for MySQL

2. No need to load MySQL driver class explicitly

3. Understand the getConnection() method of DriverManager class

4. Java code example connects to MySQL database

 

1. Download JDBC driver for MySQL

First, in order to have Java program working with MySQL, we need a JDBC driver for MySQL. Browse this URL:

http://dev.mysql.com/downloads/connector/j/

to download the latest version of the JDBC driver for MySQL called Connector/J. MySQL Connector/J comes into 2 major versions: 5.1 and 8.0. The latest version 8.0 supports JDBC 4.2 and JDK 8 or higher.

download jdbc driver for mysql

Click the Download button next to Platform Independent (Architecture Independent), ZIP Archive to download a zip archive. Extract the ZIP file to a desired location on your computer.

locate mysql-connector-java-5.1.21-bin.jar



The distribution includes a binary JAR file, source code, documentation and license files. But only one file we need is the JAR file mysql-connector-java-VERSION.jar. Copy this file into your project and make it available in your program’s classpath. You can use newer version of JDBC driver for MySQL.

If your Java project based on Maven, you just need to declare the following dependency in the pom.xml file:

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.19</version>
</dependency>
  

2. No need to load MySQL driver class explicitly

The Connector/J version 8.0 library comes with a JDBC driver class: com.mysql.cj.jdbc.Driver. Before Java 6, we have to load the driver explicitly by this statement:

Class.forName("com.mysql.cj.jdbc.Driver");

However that statement is no longer needed, thanks to new update in JDBC 4.0 comes from Java 6. As long as you put the MySQL JDBC driver JAR file  file into your program’s classpath, the driver manager can find and load the driver.

 

3. Understand the getConnection() method of DriverManager class

It’s quite easy to make a connection to a database server in general, as well as to a MySQL server in particular. Just using the method getConnection()of the class DriverManager which is available in the package java.sql.

There are three different signatures of the method getConnection()which we can use:

    • static Connection getConnection(String url)
    • static Connection getConnection(String url, Properties info)
    • static Connection getConnection(String url, String user, String password)
All three versions have a parameter called url  which is the database URL string in the following format:

 jdbc:mysql://[host][:port]/[database] [?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...

where:

    •           host: host name or IP address of the MySQL server.
    •           port: port number of the server, default is 3306.
    •           database: name of the database on the server.
    •           propertyName1=propertyValue1: a key=value pair for an additional property which will be sent to the server. For example, to send a username and password, write: ?user=root&password=secret
If a connection was made successfully with the database, the getConnection() method returns an instance of Connection class which will be used to make queries and perform other database operations.

 

4. Java code example connect to MySQL database

The following example program makes three connections to three MySQL database in three different ways:

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

public class MySQLConnectExample {
    public static void main(String[] args) {

        // creates three different Connection objects
        Connection conn1 = null;
        Connection conn2 = null;
        Connection conn3 = null;

        try {
            // connect way #1
            String url1 = "jdbc:mysql://localhost:3306/test1";
            String user = "root";
            String password = "secret";

            conn1 = DriverManager.getConnection(url1, user, password);
            if (conn1 != null) {
                System.out.println("Connected to the database test1");
            }

            // connect way #2
            String url2 = "jdbc:mysql://localhost:3306/test2?user=root&password=secret";
            conn2 = DriverManager.getConnection(url2);
            if (conn2 != null) {
                System.out.println("Connected to the database test2");
            }

            // connect way #3
            String url3 = "jdbc:mysql://localhost:3306/test3";
            Properties info = new Properties();
            info.put("user", "root");
            info.put("password", "secret");

            conn3 = DriverManager.getConnection(url3, info);
            if (conn3 != null) {
                System.out.println("Connected to the database test3");
            }
        } catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
        }
    }
}
 

NOTES: You should close the database connection in the finally clause like this:

finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
}
And since Java 1.7, you can use the try-with-resource syntax that closes the connection automatically, for example:

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

Type the following command to compile the example program:

javac MySQLConnectExample.java

Suppose the Connect/J library is placed in the same directory as the MySQLConnectExample.java file. Type the following command to run:

java -cp mysql-connector-java-5.1.21-bin.jar;. MySQLConnectExample

And here is the result when running the example program:

compile and run MySQLConnectExample

That means the program has successfully connected to the MySQL database server.

For visual howto, watch this video:

 

JDBC API References:

 

Related JDBC Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (MySQLConnectExample.java)MySQLConnectExample.java[Example program]1 kB

Add comment

   


Comments 

#29Sanjeev2022-05-02 07:52
Error: Could not find or load main class MySQLConnectExample.java
Quote
#28greg2020-12-04 04:41
Quoting Dale Wells:
I have forgotten my userid or password for MySQL. What the process of giving my database a new userid password? Thanks so much.

.....phpmyadmin/config.inc
Quote
#27Nam2020-10-18 18:18
Hi Dale Wells,
I found a good reference for you here: techrepublic.com/.../...
Quote
#26Dale Wells2020-10-17 22:42
I have forgotten my userid or password for MySQL. What the process of giving my database a new userid password? Thanks so much.
Quote
#25Gim2020-07-05 22:06
Thank Nam a lot (like)
Quote