Connecting Java to MySQL Database

Connecting Java to MySQL Database

This tutorial helps you to create a simple application using Java with MySQL DB. The below steps help you to create the application. you can learn java MySQL connection. Furthermore, you can watch my video on YouTube.

I hope you guys went through my previous article related to basic CRUD operations of the MySQL database. I suggest it is required to read because it will help to understand this article. Java with MySQL takes an important place in software engineering since most people use MySQL as their database since it is a free open-source database server.

Before going to the coding part you have to download the MySQL connector because it maintains the connectivity between your Java application and database. Once you downloaded the connector you have to add it to your project. The path is to expand your project -> right-click on libraries -> Add Jar/ Folder select the downloaded mysql-connector-java-version.jar file. Then it will be added to your project. Finally, you can start coding.

The first step is to create a DB connection it serves java MySQL connection.

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

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author bhanuka
 */
public class DBConnection {

    private Connection connection;

    public DBConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            this.connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/learnmysql", "root", "Nipun@1992");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Connection getConnection() {
        return this.connection;
    }

    public void close() {
        try {
            this.connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Secondly, you can insert the data.

import java.sql.Statement;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author bhanuka
 */
public class InsertData {

    public static void main(String[] args) {
        try {
            DBConnection connection = new DBConnection();
            final String insertQuery = "INSERT INTO learnmysql.myusers (firstname,lastname,email,regdate)"
                    + "VALUES ('Prabath','Chanaka','user5@gmail.com','2019-07-14')";
            Statement statement = connection.getConnection().createStatement();
            statement.executeUpdate(insertQuery);
            
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Then you can search for data which inserted in step 2. This is the code for search the inserted data.

import java.sql.ResultSet;
import java.sql.Statement;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author bhanuka
 */
public class SearchData {

    public static void main(String[] args) {
        try {
            DBConnection connection = new DBConnection();
            final String selectQuery = "SELECT * FROM learnmysql.myusers WHERE id =5";
            Statement statement = connection.getConnection().createStatement();
            ResultSet rs = statement.executeQuery(selectQuery);

            while (rs.next()) {
                System.out.println("First Name : " + rs.getString("firstname"));
                System.out.println("Second Name : " + rs.getString("lastname"));
            }

            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This is the code for update the data.

import java.sql.Statement;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author bhanuka
 */
public class UpdateData {
     public static void main(String[] args) {
        try {
            DBConnection connection = new DBConnection();
            final String updateQuery = "UPDATE learnmysql.myusers SET email = 'bhanuka@gmail.com' WHERE id = 4";
            Statement statement = connection.getConnection().createStatement();
            statement.executeUpdate(updateQuery);
            
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This code block for delete the data.

import java.sql.Statement;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author bhanuka
 */
public class DeleteData {

    public static void main(String[] args) {
        try {
            DBConnection connection = new DBConnection();
            final String deleteQuery = "DELETE FROM learnmysql.myusers WHERE id =5";
            Statement statement = connection.getConnection().createStatement();
            statement.executeUpdate(deleteQuery);

            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

GIT Location – https://github.com/rajithabhanuka/LearnMysql.git