Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

How to Perform CRUD Operations on MySQL Database using Java

[post-views]

 

 

In this lesson, you will learn.

  • Performing CRUD Operations
  • Example

 

What are CRUD Operations

The abbreviation CRUD stands for create, read, update, and delete in computer programming.

 

Statement Interface

The Statement interface in Java JDBC provides several methods for executing SQL queries and updating the database.

These methods can be broadly categorized into three types:

  1. Executing Queries that Return Result Sets
  2. Executing Updates that Modify Data
  3. Executing General SQL Statements

 

1. executeQuery(String sql)

  1. Used for SELECT statements that query the database.
  2. Returns a ResultSet object containing the results of the query.

 

Statement statement = connection.createStatement();
String query = "SELECT * FROM employees";
ResultSet resultSet = statement.executeQuery(query);

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

 

2. executeUpdate(String sql)

  1. Used for INSERT, UPDATE, DELETE, and DDL statements (e.g., CREATE TABLE, ALTER TABLE).
  2. Returns an int indicating the number of rows affected, or 0 for statements that return nothing.

 

Statement statement = connection.createStatement();
String update = "UPDATE employees SET salary = 50000 WHERE id = 1";
int rowsAffected = statement.executeUpdate(update);
System.out.println("Rows affected: " + rowsAffected);

 

3. execute(String sql)

  1. Used when the SQL statement may return multiple result sets and/or update counts.
  2. Returns a boolean: true if the first result is a ResultSet object; false if it is an update count or there are no results.

 

Statement statement = connection.createStatement();
String sql = "SELECT * FROM employees";
boolean isResultSet = statement.execute(sql);

if (isResultSet) {
    ResultSet resultSet = statement.getResultSet();
    while (resultSet.next()) {
        int id = resultSet.getInt("id");
        String name = resultSet.getString("name");
        System.out.println("ID: " + id + ", Name: " + name);
    }
} else {
    int updateCount = statement.getUpdateCount();
    System.out.println("Update count: " + updateCount);
}

 

4. addBatch(String sql)

  1. Used to batch multiple SQL statements together for execution.
  2. Executes the batch using the executeBatch method.

 

Statement statement = connection.createStatement();
statement.addBatch("INSERT INTO employees (name, salary) 
VALUES ('John Doe', 50000)");
statement.addBatch("INSERT INTO employees (name, salary) 
VALUES ('Jane Smith', 60000)");
int[] updateCounts = statement.executeBatch();

for (int count : updateCounts) {
    System.out.println("Rows affected: " + count);
}

 

Example – Creating a Table

 

Prerequisites:

Use MySQL to create a database schema named ‘jcodebookdb’ by using the following SQL command.

CREATE DATABASE jcodebookdb;

 

package createtable;

import java.sql.*;
public class CreateTable {
	static String url = "jdbc:mysql://localhost:3306/jcodebookdb";
	public static void main(String[] args) {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			Connection con=DriverManager.getConnection(url, "root","root");
			String sql="CREATE TABLE users(id INT AUTO_INCREMENT PRIMARY KEY,"
					+ "name VARCHAR(100),email VARCHAR(100),country VARCHAR(100),"
					+ "password VARCHAR(100));";
			Statement stmt = con.createStatement();	
			int i=stmt.executeUpdate(sql);
			if(i==0) {
				System.out.println("Table created");
			}
			else {
				System.out.println("Table not created");
			}
		}
		catch(Exception e) {	
			System.out.println(e);
		}
	}
}

 

Output

Table created

 

Open the MySQL database and check the table named ‘users’ is created.

 


 

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