How to connect Java with MySQL

Author:

Lucas Estefano - Full-Stack developer

Let’s connect:  Linkedin

How to connect Java With MYSQL

I recently resumed my studies with the feared by many, JAVA!

I had contact with Java during college where I completed two projects. My goal now is to focus on Object-Oriented Programming – POO studies. Therefore, I am resuming my studies on this great technology, with a focus on creating robust applications and enhancing my knowledge in POO, Microservices, etc…

My goal, after a few months of studying pure Java, is to learn more about “Spring Boot,” which is a tool that facilitates and accelerates the development of web applications and microservices with the Spring Framework. If you’d like to read more detailed information about this technology, I recommend starting with the official documentation below:

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#getting-started

book

With the aim of enhancing knowledge of interaction between Java and databases, I created this article with a step-by-step guide that I used to establish a connection between Java and the MySql/MariaDB database.

1- You need to have MySql installed in your test/study environment. You basically have two ways to install the MySql database:

    1st –  By using the official MySQL website to download, install, and configure the database:

    – Direct download link for MySQL from the official website:

     https://www.mysql.com/downloads/

 

    2nd – Alternatively, to simplify the installation process, you can use “Xampp.”:

 – Xampp is commonly used for PHP development and provides convenience by skipping the more complicated configuration steps.

 – Xampp Download Link:

https://www.apachefriends.org/download.html

After installation, simply click on the database service button and it will start running.

The access data for the database with Xampp are:
IP: localhost:3306
User: “root”
Password: “” (blank)

1.1 – Xampp

1.2 – To start the database, you must click on “Start” for Apache and “Start” for MySQL.

 

1.3 – It should run as follows after the Start:

Additionally, with Xampp, you can use PhpMyAdmin, which is an SQL client. If you wish, you can use the credentials I provided earlier to connect to your preferred SQL client. I usually use DBever or Workbench for certain tasks.

1.4 – PhpMyAdmin:

2- After having the database installed and configured, you need to download the MysqlConnector library (.jar file) to import into your project and make the library available for use in your Java code.

3- Use the link below to download the library that is working as of the date of this post. If you encounter any issues with this version, simply search on Google for “mysql connector-java” and download it from the official MySQL website.

Download link: https://drive.google.com/file/d/1K8qzUh77THb7UhU3S8-nEDM8PPtIH4HY/view?usp=sharing
Remember: You should use the .jar file.

4- After downloading, you need to create a folder to store all the downloaded libraries. I am using the following path:

Inside the: C:// drive, I created the folder “java-libs”,

and inside it, I created the folder “jdbc-connectors”. It looks like this:

Path: “C:\java-libs\jdbc-connectors”

5- After completing step 4, we now need to add the library to Intellij or any other IDE you are using. Follow these steps:

   5.1 – Open Intellij.

   5.2 – Start a new JAVA project:

   Click on “File -> New -> Project”.

   5.3 – Define a name for your project, in my case:

   ConnectionBD, then click on “Create”.

   5.4 – Now, let’s add the library we downloaded and placed in the folder:

   “C:\java-libs\jdbc-connectors”.

   With the new project open, click on “File -> Project Structure”.

   5.5 – Click on:

“Libraries -> + -> JAVA -> the path where we placed the downloaded file”,

in my case “C:\java-libs\jdbc-connectors\mysql-connector.jar”.

Then click on OK -> OK -> Apply -> OK again.

   5.6 – Great, the library has been added to the project! If we look at the right corner of Intellij, we will see the “mysql-connector” library under “External Libraries”, as shown in the image below:

6- Finally, we enter the coding stage!

   6.1 – We need to create our database connection class. Right-click on the “SRC” folder, then click on “New -> Java Class”.

   6.2 – Set the name of the class as:

   “ConnectionBD”.

   6.3 – Inside the created class, insert the code:

   “public static void main(String[] args) { }.”

   In this way, this will be the first file to run in the project.

				
					public class ConnectionBD {
    public static void main(String[] args) {
        
    }
}

				
			

   6.4 Complete code:

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

public class ConnectionBD {
    public static void main(String[] args) throws SQLException {
        Connection connectBD = null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            String username = "root";
            String password = "";
            connectBD = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_connection_bd", username, password);
            ResultSet rsClient = connectBD.createStatement().executeQuery("SELECT * FROM persons; ");

            while (rsClient.next()){
                // Columns database:
                String personId = rsClient.getString("PersonId");
                String lastName = rsClient.getString("LastName");
                String firstName = rsClient.getString("FirstName");
                String adrdess = rsClient.getString("Address");
                String city = rsClient.getString("City");

                //Data BD:
                System.out.println("The person id is: " + personId + ",\n lastname: " + lastName + ",\n firstname: " + firstName + ",\n address: " + adrdess);

                            }
        }catch (ClassNotFoundException ex){
            System.out.println("DB driver not found");
        } catch (SQLException e) {
            System.out.println("Was an error accessing the database " + e.getMessage());
        }finally {

            // Close connection:
            if(connectBD != null) {
                connectBD.close();
            }

        }
    }
}


				
			

   6.5 Database:

   6.6: Result:

Ready! ✅

From here on, it’s just a matter of handling the returned data and using it as needed!

 

Learn more:

  • What is JDBC?
    JDBC (Java Database Connectivity) is a Java API that allows Java programs to connect to relational databases. It provides a set of classes and interfaces that facilitate the interaction between a Java program and a database. JDBC enables developers to create Java applications that can execute queries, updates, and other operations on a database. This API is widely used for developing applications that involve accessing data in databases.

One thought on “How to connect Java with MySQL”

Leave a Reply

Your email address will not be published. Required fields are marked *