Pre Course Home Next

Java Tutorial

Java Connect With MySQL Database

In this tutorial we will see how to make connection with MySQL database using Java. MySQL is a major open-source free database and it is widely used in various types of applications.

Prerequisites

Before running the below code samples, you must ensure that the MySQL connector/j is already installed on your system and "classpath" is already set.

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/mydatabasename?useSSL=false";
        String databseUserName = "yourdbusername"; // eg: root
        String databasePassword = "yourdbpassword"; //eg: 123456
        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
        }
    }
}

 

Output:

Database connection is successful !!!!

This is how we can connect to MySQL database. Further you can try to fetch data from the database.

Pre Course Home Next