📜  CRUD JAVA (1)

📅  最后修改于: 2023-12-03 15:30:07.555000             🧑  作者: Mango

CRUD Java

Java is a popular programming language that is widely used for creating scalable and robust applications. CRUD (Create, Read, Update, Delete) operations are the basic operations that every application needs. In this article, we will discuss how to perform CRUD operations in Java.

Create

Creating a new record in the database is the 'Create' operation. In Java, we can use JDBC (Java Database Connectivity) to perform database operations. Here's a sample code snippet that demonstrates how to create a new record in a MySQL database.

import java.sql.*;

public class CreateUser {
    public static void main(String args[]) {
        try {
            // Load MySQL JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Connect to MySQL Database
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test?useSSL=false", "root", "password");

            // Prepare SQL Statement
            String sql = "INSERT INTO users (id, name, email) VALUES (?,?,?)";
            PreparedStatement statement = con.prepareStatement(sql);

            // Set Parameters
            statement.setInt(1, 1);
            statement.setString(2, "John Doe");
            statement.setString(3, "johndoe@example.com");

            // Execute Statement
            statement.executeUpdate();

            // Close Connection
            con.close();
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
Read

Reading data from the database is the 'Read' operation. Here's a sample Java code snippet that demonstrates how to read data from a MySQL database.

import java.sql.*;

public class ReadUser {
    public static void main(String args[]) {
        try {
            // Load MySQL JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Connect to MySQL Database
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test?useSSL=false", "root", "password");

            // Prepare SQL Statement
            String sql = "SELECT * FROM users";
            Statement statement = con.createStatement();

            // Execute Statement
            ResultSet resultSet = statement.executeQuery(sql);

            // Process Results
            while(resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String email = resultSet.getString("email");
                System.out.println("ID: " + id + " | Name: " + name + " | Email: " + email);
            }

            // Close Connection
            con.close();
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
Update

Updating a record in the database is the 'Update' operation. Here's a sample Java code snippet that demonstrates how to update a record in a MySQL database.

import java.sql.*;

public class UpdateUser {
    public static void main(String args[]) {
        try {
            // Load MySQL JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Connect to MySQL Database
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test?useSSL=false", "root", "password");

            // Prepare SQL Statement
            String sql = "UPDATE users SET name=?, email=? WHERE id=?";
            PreparedStatement statement = con.prepareStatement(sql);

            // Set Parameters
            statement.setString(1, "Jane Doe");
            statement.setString(2, "janedoe@example.com");
            statement.setInt(3, 1);

            // Execute Statement
            statement.executeUpdate();

            // Process Results
            System.out.println("Record updated successfully!");

            // Close Connection
            con.close();
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
Delete

Deleting a record from the database is the 'Delete' operation. Here's a sample Java code snippet that demonstrates how to delete a record from a MySQL database.

import java.sql.*;

public class DeleteUser {
    public static void main(String args[]) {
        try {
            // Load MySQL JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Connect to MySQL Database
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test?useSSL=false", "root", "password");

            // Prepare SQL Statement
            String sql = "DELETE FROM users WHERE id=?";
            PreparedStatement statement = con.prepareStatement(sql);

            // Set Parameters
            statement.setInt(1, 1);

            // Execute Statement
            statement.executeUpdate();

            // Process Results
            System.out.println("Record deleted successfully!");

            // Close Connection
            con.close();
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}

In summary, CRUD operations are essential to database programming, and Java provides various libraries to handle these operations. By using JDBC, Java developers can easily create, read, update, and delete data in a database.