Skip to content

Connect With MySQL Database using Java

In this tutorial we will see how to make connection with MySQL database in Java programming language. As like Java language is open-source, MySQL is also an open-source database and it is also the preferred database along with Oracle in database section.

Prerequisites

Before running the below code samples, you must ensure that you have already installed MySQL connector/j is on your system and “classpath” is already set. If not, then follow the official site for setting these up.

Connecting to a MySQL database with Java

To connect to MySQL database using JDBC, you can use below code sample:

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

// Notice, do not import com.mysql.jdbc.* , or you will have problems!

public class JDBCTest {
    public static void main(String[] args) {
        String MySQLURL = "jdbc:mysql://localhost:3306/yourdatabasename?useSSL=false";
        String databseUserName = "yourdbusername"; // eg: root
        String databasePassword = "yourdbpassword";
        Connection con = null;
        try {
            // The newInstance() call is a work around for some broken Java implementations

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

            con = DriverManager.getConnection(MySQLURL, databseUserName, databasePassword);
            if (con != null) {
               System.out.println("Database connection is successful.");
            }
        } catch (Exception ex) {
            // handle the error
        }
    }
}

And the output is:

Database connection is successful.

This is how we can connect MySQL database using JDBC driver in Java programming language.

Be First to Comment

Leave a Reply

Your email address will not be published.