Java connect to MySQL database with JDBC

  • September 4, 2022
  • Java
java thread class

Follow the steps below to connect a Java application to a MySQL database using the JDBC Driver.

  • Download JDBC driver for MySQL
  • No need to load MySQL driver class explicitly
  • Understand the getConnection() method of DriverManager class
  • Java code example connects to MySQL database
Download JDBC driver for MySQL:

To begin, a JDBC driver for MySQL is required for a Java program to communicate with MySQL. To download the latest version of the JDBC driver for MySQL, go to this URL: http://dev.mysql.com/downloads/connector/j/

MySQL Connector/J is available in two major versions: 5.1 and 8.0. JDBC 4.2 and JDK 8 or higher are supported in the latest version 8.0.

download jdbc driver for mysql

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

A binary JAR file, source code, documentation, and license files are included in the distribution. However, only one file is required: the JAR file mysql-connector-java-VERSION.jar. Copy this file into your project and include it in the classpath of your program. You can use a more recent version of the JDBC driver for MySQL.

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 required due to new Java 6 updates in JDBC 4.0. If you include the MySQL JDBC driver JAR file in your program’s classpath, the driver manager will be able to find and load it.

Understand the getConnection() method of DriverManager class:

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: hostname 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 that will be sent to the server. For example, to send a username and password, write: ?user=root&password=secret
Java code example connects to MySQL database:

The following example program connects to three different MySQL databases 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();
        }
    }
}

Note: also read about the Java Database Connectivity

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *