How to Connect a MySQL Database in Java

Mohammad Irfan Feb 02, 2024
  1. Download and Install MySQL Database
  2. Create a DataBase in MySQL
  3. Download the JDBC Driver and Include It in the Classpath
  4. Connect With MySQL
  5. Test the JDBC Connection
How to Connect a MySQL Database in Java

This tutorial introduces how to connect a MySQL database in Java. We’ve also listed some example codes so that you can understand this topic further.

To connect the Java application a the Mysql database, we need to follow some steps that are listed below:

  • Download and Install MySQL
  • Create a dataBase in MySQL
  • Download the JDBC Driver and put it in the classpath
  • Write the Java Code for connectivity
  • Test the connection

Let’s understand the step-by-step procedure here:

Download and Install MySQL Database

MySQL is a database management system, and we assume that you already have installed it. Let’s move to the next step.

Create a DataBase in MySQL

Now, we will create a database so that we can test the connection. To create a database in MySQL, use the SQL query below:

create database delftstackDB;

After creating a database, remember it because you’ll use it in the connectivity part.

Download the JDBC Driver and Include It in the Classpath

The JDBC Driver is a JAR file provided by MySQL; it’s a connector that acts as a bridge between MySQL and Java applications. To download the JAR file visit the MySQL official site and place the files into the lib folder of your java project. Now, proceed to the next step.

Connect With MySQL

After completing the procedures above, write the Java code for connectivity. Here, we used the class.forName() method to load the JDBC Driver, which we downloaded from the MySQL official site.

The getConnection() method is used to pass the connection string: MySQL:Port/Database/,username,dbpassword. This string is used to authenticate the user and provide access to authorized users only. After that, we used the createStatement() method to create an instance that will be used to execute SQL queries by using the code. See the example below:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SimpleTesting {
  public static void main(String[] args) {
    try {
      Class.forName("com.mysql.jdbc.Driver");
      Connection con = DriverManager.getConnection(
          "jdbc:mysql://localhost:3306/delftstackDB", "username", "dbPassword");
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("show databases;");
      System.out.println("Connected");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

Test the JDBC Connection

After writing the code, you just have to execute it. If the code runs fine, then you’ll get the following output to the console:

Output:

Connected

Related Article - Java Database