Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Eclipse IDE: Connecting Java Program With MySQL Database using JDBC API

In this lesson, you will learn.

  • Connecting a Java Program with a MySQL Database using the JDBC API.
  • Example

 

Connecting a Java Program with a MySQL Database using the JDBC API

To connect a Java program with a MySQL database using the JDBC (Java Database Connectivity) API, follow these steps:

 

Step-1: Importing The Packages

First, you need to import the necessary JDBC packages. All the JDBC APIs are defined in the java.sql package.

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

 

Step 2: Load and Register the JDBC Driver

For MySQL, you need to load the MySQL JDBC driver. Ensure you have the MySQL JDBC driver (mysql-connector-java.jar) in your classpath.

The forName() method of the java.lang.Class class loads the JDBC driver and registers the driver with the following syntax.

try {
    Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

 

Step 3: Establish a Connection

Create a connection to the database using the DriverManager class.

The DriverManager class provides the getConnection() method to create a Connection object.

String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
String username = "yourUsername";
String password = "yourPassword";

Connection connection = null;

try {
	connection = DriverManager.getConnection(
			url, username, password);
	System.out.println("Connection established successfully.");
} catch (SQLException e) {
	e.printStackTrace();
}

 

DriverManager.getConnection(String url, String user, String password): Attempts to establish a connection to the given database URL.

 

Step 4: Create a Statement

Create a Statement object to send SQL statements to the database. There are three types of statements: Statement, PreparedStatement, and CallableStatement.

Statement statement = null;

try {
    statement = connection.createStatement();
} catch (SQLException e) {
    e.printStackTrace();
}

 

Connection.createStatement(): Creates a Statement object for sending SQL statements to the database.

 

Step 5: Execute a Query

Execute an SQL query using the Statement object. You can execute queries that return a ResultSet object or update statements.

String query = "SELECT * FROM yourTableName";
ResultSet resultSet = null;

try {
    resultSet = statement.executeQuery(query);
} catch (SQLException e) {
    e.printStackTrace();
}

 

Statement.executeQuery(String sql): Executes the given SQL statement, which returns a single ResultSet object.

 

Step 6: Process the Result Set

Process the results returned by the query. The ResultSet object provides methods to navigate through and retrieve data from the result set.

try {
    while (resultSet.next()) {
        int id = resultSet.getInt("id");
        String name = resultSet.getString("name");
        System.out.println("ID: " + id + ", Name: " + name);
    }
} catch (SQLException e) {
    e.printStackTrace();
}

 

  • ResultSet.next(): Moves the cursor forward one row from its current position.
  • ResultSet.getInt(String columnLabel): Retrieves the value of the designated column in the current row of this ResultSet object as an int.
  • ResultSet.getString(String columnLabel): Retrieves the value of the designated column in the current row of this ResultSet object as a String.

 

Step 7: Close the Connection

Close the ResultSet, Statement, and Connection objects to free up database resources.

try {
    if (resultSet != null) resultSet.close();
    if (statement != null) statement.close();
    if (connection != null) connection.close();
    System.out.println("Connection closed successfully.");
} catch (SQLException e) {
    e.printStackTrace();
}

 

How to Connect Java Program with MySQL Database Using Eclipse

Prerequisites

Install the following software

  1. Eclipse IDE or Any Java Supported IDE
  2. MySQL Database https://dev.mysql.com/downloads/installer/

 

Step 1: Create a Database Schema and a Data Table

Open the MySql database and write the following Queries to create an Employee data table in the jcodebook database.

-- Creating a Database
create database jcodebook;
 
-- Enabling the Database for Use
use jcodebook;
 
-- Creating a Table
CREATE TABLE Employees (
    EmployeeID int PRIMARY KEY,
    Name varchar(255) NOT NULL,
    BirthDate date,
    Salary decimal(10, 2)
);

-- 1. INSERT
INSERT INTO Employees 
(EmployeeID, Name, BirthDate, Salary)
VALUES (1, 'John', '1980-01-15', 60000);
 
-- Inserting Multiple Rows
INSERT INTO Employees 
(EmployeeID, Name, BirthDate, Salary)
VALUES
(2, 'Jane', '1985-02-20', 65000),
(3, 'Michael', '1990-03-10', 55000);

 

Step 2: Download  and Configure MySQL Java Connector

Use the https://downloads.mysql.com/archives/c-j/  link to download the MySQL Java connector as shown below.

 

 

Extract the mysql-connector-j-8.0.33 file, copy the mysql-connector-j-8.0.33 jar file, and add it to your project.

For example, your Java project name is ‘Lecture 14 – JDBC’.

Add the mysql-connector-j-8.0.33 in the project build path as shown in the figure below.

 

 

 

 

 

Example: Fetching Data From MySQL Database using a Java Program

package fetchdatafrommysql;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class FetchDataFromMySQL {

	public static void main(String[] args) {
		String url = "jdbc:mysql://localhost:3306/jcodebook?serverTimezone=UTC";
		try {
			// Step 1: Import JDBC Packages (done above)

			// Step 2: Load and Register JDBC Driver
			Class.forName("com.mysql.cj.jdbc.Driver");
			// Step 3: Establish a Connection
			Connection con=DriverManager.getConnection(url, "root","root");
			// Step 4: Create a Statement
			Statement stmt = con.createStatement();	
			// Step 5: Create and Execute a Query
			String sql="Select * from Employees";
			ResultSet rs=stmt.executeQuery(sql);
			System.out.println("EmpIDtFirstNametBirthDatetSalary");
			// Step 6: Process the Result Set
			while(rs.next()) {
				int empID = rs.getInt(1);
				String fname =  rs.getString(2);
				Date bdate = rs.getDate(3);
				double salary = rs.getDouble(4);

				System.out.println(empID+"t"+fname+"tt"+bdate+"t"+salary);
			}
			// Step 7: Close the Connection
			con.close();stmt.close();rs.close();
		}
		catch(Exception e) {	
			System.out.println(e);
		}
	}
}

 

Output

 

 

 

 

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review

 

 

 

Layer 1
Login Categories