Java tutorial with CRUD examples

 

Java CRUD Tutorial with Examples

In this tutorial, we'll cover how to perform CRUD operations (Create, Read, Update, Delete) in Java using JDBC (Java Database Connectivity) and a MySQL database. We'll walk through setting up the database, creating a Java application to interact with the database, and performing the basic CRUD operations.


1. Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed.
  • MySQL database running.
  • MySQL Connector/J for JDBC (used to connect Java to MySQL).
  • IDE like IntelliJ IDEA, Eclipse, or Visual Studio Code for writing Java code.

2. Setting Up the MySQL Database

We'll start by creating a database and a table called Users to perform CRUD operations.

  1. Create a MySQL Database: Open MySQL Workbench or any MySQL client, and run the following SQL commands to create the database and a Users table.
sql
CREATE DATABASE CrudExample; USE CrudExample; CREATE TABLE Users ( id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(100) );

This creates a Users table with the following columns:

  • id: A unique identifier for each user (Primary Key).
  • first_name: The first name of the user.
  • last_name: The last name of the user.
  • email: The email address of the user.
  1. Insert some sample data into the table (optional):
sql
INSERT INTO Users (first_name, last_name, email) VALUES ('John', 'Doe', 'john.doe@example.com'); INSERT INTO Users (first_name, last_name, email) VALUES ('Jane', 'Smith', 'jane.smith@example.com');

3. Add MySQL JDBC Driver

To connect Java with MySQL, we need to add the MySQL JDBC driver to the project.

  • If you're using Maven, add this dependency in your pom.xml:
xml
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> <!-- Use the latest version available --> </dependency>
  • If you're using IntelliJ IDEA, you can also add the jar file directly or use Maven/Gradle to manage dependencies.

4. Create a Java Program for CRUD Operations

Now, let’s create a Java program to perform CRUD operations on the Users table.

  1. Import Required Libraries:
java
import java.sql.*; import java.util.Scanner;
  1. Database Connection Setup:

To interact with the MySQL database, we'll create a utility method to establish a connection.

java
public class DatabaseHelper { private static final String URL = "jdbc:mysql://localhost:3306/CrudExample"; private static final String USER = "root"; // Your MySQL username private static final String PASSWORD = "password"; // Your MySQL password public static Connection connect() throws SQLException { return DriverManager.getConnection(URL, USER, PASSWORD); } }

5. CRUD Operations in Java

Now, let’s implement the actual CRUD operations.

Create Operation (INSERT)

java
public class UserOperations { // Create User public void createUser(String firstName, String lastName, String email) { String query = "INSERT INTO Users (first_name, last_name, email) VALUES (?, ?, ?)"; try (Connection connection = DatabaseHelper.connect(); PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setString(1, firstName); stmt.setString(2, lastName); stmt.setString(3, email); int rowsAffected = stmt.executeUpdate(); System.out.println("User added successfully! Rows affected: " + rowsAffected); } catch (SQLException e) { System.err.println("Error: " + e.getMessage()); } } }
  • PreparedStatement: Used to avoid SQL injection and securely insert data into the database.

Read Operation (SELECT)

java
public void readUsers() { String query = "SELECT * FROM Users"; try (Connection connection = DatabaseHelper.connect(); Statement stmt = connection.createStatement(); ResultSet resultSet = stmt.executeQuery(query)) { while (resultSet.next()) { int id = resultSet.getInt("id"); String firstName = resultSet.getString("first_name"); String lastName = resultSet.getString("last_name"); String email = resultSet.getString("email"); System.out.println("ID: " + id + ", Name: " + firstName + " " + lastName + ", Email: " + email); } } catch (SQLException e) { System.err.println("Error: " + e.getMessage()); } }
  • ResultSet: Holds the result set of the SELECT query.
  • Statement: Used for executing simple queries.

Update Operation (UPDATE)

java
public void updateUser(int id, String firstName, String lastName, String email) { String query = "UPDATE Users SET first_name = ?, last_name = ?, email = ? WHERE id = ?"; try (Connection connection = DatabaseHelper.connect(); PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setString(1, firstName); stmt.setString(2, lastName); stmt.setString(3, email); stmt.setInt(4, id); int rowsAffected = stmt.executeUpdate(); if (rowsAffected > 0) { System.out.println("User updated successfully!"); } else { System.out.println("No user found with ID " + id); } } catch (SQLException e) { System.err.println("Error: " + e.getMessage()); } }
  • executeUpdate(): Executes queries that modify the database (e.g., INSERT, UPDATE, DELETE).

Delete Operation (DELETE)

java
public void deleteUser(int id) { String query = "DELETE FROM Users WHERE id = ?"; try (Connection connection = DatabaseHelper.connect(); PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); int rowsAffected = stmt.executeUpdate(); if (rowsAffected > 0) { System.out.println("User deleted successfully!"); } else { System.out.println("No user found with ID " + id); } } catch (SQLException e) { System.err.println("Error: " + e.getMessage()); } }
  • DELETE FROM: Deletes records from the database based on a condition (here, WHERE id = ?).

6. Main Method to Test CRUD Operations

Now, let’s add a simple main method to interact with the user and perform the CRUD operations.

java
import java.util.Scanner; public class CRUDApp { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); UserOperations userOps = new UserOperations(); while (true) { System.out.println("\nChoose an option: "); System.out.println("1. Create User"); System.out.println("2. Read Users"); System.out.println("3. Update User"); System.out.println("4. Delete User"); System.out.println("5. Exit"); System.out.print("Enter your choice: "); int choice = scanner.nextInt(); scanner.nextLine(); // Consume the newline character switch (choice) { case 1: // Create User System.out.print("Enter First Name: "); String firstName = scanner.nextLine(); System.out.print("Enter Last Name: "); String lastName = scanner.nextLine(); System.out.print("Enter Email: "); String email = scanner.nextLine(); userOps.createUser(firstName, lastName, email); break; case 2: // Read Users userOps.readUsers(); break; case 3: // Update User System.out.print("Enter User ID to Update: "); int updateId = scanner.nextInt(); scanner.nextLine(); // Consume the newline System.out.print("Enter First Name: "); String updatedFirstName = scanner.nextLine(); System.out.print("Enter Last Name: "); String updatedLastName = scanner.nextLine(); System.out.print("Enter Email: "); String updatedEmail = scanner.nextLine(); userOps.updateUser(updateId, updatedFirstName, updatedLastName, updatedEmail); break; case 4: // Delete User System.out.print("Enter User ID to Delete: "); int deleteId = scanner.nextInt(); userOps.deleteUser(deleteId); break; case 5: // Exit System.out.println("Exiting the application."); scanner.close(); return; default: System.out.println("Invalid choice. Please try again."); } } } }

7. Running the Program

  • Compile and run the CRUDApp.java file.
  • You can test the CRUD operations by choosing the corresponding menu options:
    1. Create a new user.
    2. Read and display all users.
    3. Update a user’s information.
    4. Delete a user by ID.

    5. 8. Conclusion

      In this tutorial, we:

      • Set up a MySQL database and a Users table.
      • Implemented Create, Read, Update, and Delete operations using JDBC.
      • Created a simple console application in Java to interact with the database.

      This basic structure can be expanded to build more complex applications by adding error handling, validation, and more advanced features like transactions or using an ORM (Object-Relational Mapping) tool like Hibernate.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics