Skip to content

JDBC Connection with MySQL Database

"How do I set up this connection?" Don't worry, it's simpler than you think. All you need is the right driver and a bit of code magic.

First things first, you'll need to make sure you have the MySQL JDBC driver. This little guy acts as the translator between Java and MySQL. You can easily download it from the MySQL website and add it to your Java project.

Once you've got the driver sorted, it's time to write some code! But hey, no need to stress. We'll take it step by step. We'll establish the connection, execute queries, and handle the results, all in plain and simple Java.

Adding MySQL Driver

Using Maven:

If you're using Maven for your project management, adding the MySQL JDBC driver is a breeze. You just need to include the dependency for the MySQL connector in your project's pom.xml file. Maven will take care of fetching and managing the driver for you.

    <version>{version}</version> <!-- Replace {version} with the specific version you need -->

Simply replace {version} with the version of the MySQL connector you want to use, and Maven will handle the rest.

Using Gradle:

For those using Gradle as their build tool, adding the MySQL JDBC driver is just as straightforward. You'll need to add the dependency to your build.gradle file.

implementation 'mysql:mysql-connector-java:{version}' // Replace {version} with the specific version you need

Similar to Maven, Gradle will automatically fetch the MySQL connector for you based on the specified version.

Using JAR File:

If you prefer managing dependencies manually or if your project setup doesn't involve Maven or Gradle, you can still add the MySQL JDBC driver by downloading the JAR file from the MySQL website.

Once you have the JAR file, simply include it in your project's build path. You can do this by placing the JAR file in the lib directory of your project and then adding it to your project's build path in your IDE.

Creating Database

Before we jump into connecting Java with MySQL, there are a couple of things we need to ensure. First off, make sure you have your MySQL server up and running. If you haven't installed MySQL yet, you can download and install it from the official MySQL website. Once installed, start the MySQL server on your machine.

Next, ensure that you have a database created in your MySQL server. A database is like a container for your data, where you can organize and store information in various tables. If you haven't created a database yet, no worries! We'll walk through it quickly.

You can use a tool like MySQL Workbench, phpMyAdmin, or even the MySQL command line to create a database. Let's say we want to create a database named "my_database". Here's how you can do it using MySQL Workbench:

  1. Open MySQL Workbench and connect to your MySQL server.
  2. Once connected, you'll see an option to create a new schema (which is MySQL's term for a database). Click on it.
  3. Give your new database a name, such as "my_database", and click apply.

Connect with database

Sure, let's continue building on the previous steps:

Now that you have your MySQL server running and a database created, let's connect to it using Java JDBC. We'll write a simple example to establish the connection with the database we just created.

First, make sure you have the MySQL JDBC driver added to your project as we discussed earlier, either through Maven, Gradle, or by manually adding the JAR file.

Now, let's dive into the Java code. Below is a basic example of how to connect to the MySQL database "my_database" using JDBC:

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

public class Main {
    public static void main(String[] args) {
        // Database credentials
        String url = "jdbc:mysql://localhost:3306/my_database";
        String username = "your_username"; // Replace with your MySQL username
        String password = "your_password"; // Replace with your MySQL password

        // Try to establish the connection
        try {
            // Register MySQL JDBC driver

            // Open a connection
            Connection connection = DriverManager.getConnection(url, username, password);
            // Check if the connection is successful
            if (connection != null) {
                System.out.println("Connected to the database!");
                // You can perform database operations here
                // For example, executing queries, inserting data, etc.
                // Don't forget to close the connection when you're done
        } catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found!");
        } catch (SQLException e) {
            System.out.println("Connection failed! Check output console");

In this example:

  • We specify the URL of our MySQL database ("jdbc:mysql://localhost:3306/my_database"), where "my_database" is the name of the database we created earlier.
  • We provide the username and password to authenticate with the MySQL server.
  • We attempt to establish a connection using DriverManager.getConnection(url, username, password).
  • If the connection is successful, we print a message confirming the successful connection.

Remember to replace "your_username" and "your_password" with your actual MySQL username and password.

Common error while connecting to MySQL

Even though connecting Java with MySQL using JDBC is straightforward, you might encounter a few bumps along the way. Here are some common errors you might run into during the connection process:

  1. ClassNotFoundException for MySQL JDBC Driver: This error occurs when Java cannot find the MySQL JDBC driver. Make sure you have added the MySQL connector JAR to your project's classpath correctly. If you're using Maven or Gradle, ensure that the dependency is correctly specified in your pom.xml or build.gradle file.

  2. SQLException - Connection Refused: If you're getting a "Connection refused" error, it means that Java is unable to establish a connection to the MySQL server. Double-check that your MySQL server is running and that you've provided the correct hostname, port, username, and password in your connection URL.

  3. SQLException - Access Denied: This error occurs when the username or password you've provided in the connection URL is incorrect, or the user doesn't have sufficient privileges to access the database. Make sure you've entered the correct username and password, and that the user has the necessary permissions to connect to the database.

  4. SQLException - Unknown Database: If you're getting an "Unknown database" error, it means that the database name specified in your connection URL doesn't exist on the MySQL server. Double-check the name of the database in your URL and ensure that you've created the database with the correct name.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.