Skip to content

How to Connect to MySQL with Java JDBC driver

This article will go over how to connect to MySQL with the Java JDBC driver. The tutorial will go over step-by-step on how to make your first connection with the Java JDBC driver to MySQL and get started.

Installation of MySQL

For starters, you must have MySQL on your machine. To install MySQL, you can easily use the following command on Ubuntu or Debian machines:

sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo mysql -u root -ppassword


Create a MySQL database

After entering into the mysql command line, you can start by creating a new MySQL database for use:

create database jdbc;
use jdbc;

Now, you’re using the jdbc database. You can create a new user instead of root to use this database.

We’ve given permissions for the jdbcuser.

Now, we’ll also be creating a sample database so that you can try the MySQL JDBC driver.


Installation of MySQL JDBC driver

You will need to install the MySQL JDBC driver. The latest JDBC driver can be found at:


Java JDBC Project

We create a Java project and package called com.slothparadise.jdbcproject.

We create a folder named lib inside the project and copy the JDBC driver into this folder so that we can use the driver. Make sure to copy the .jar file from the downloaded JDBC driver into the lib folder. On Eclipse, you can use File, Import, General, File System. Select the lib folder that you had created to import.

Now, we must adjust the classpath. On Eclipse, you can do so by right clicking on the JAR file and selecting Build Path, Add to Build Path.


Sample Java Class project

We will start by creating a new Java class for our project. I will create a class called JDBCExample.

The following prints the data from the MySQL database from the JDBC driver.


Run the program

When you run the program with this class, it will print out the contents of the MySQL database twice.