CRUD stands for Create, Read, Update, and Delete – the four basic operations used to interact with a database. Using JDBC (Java Database Connectivity), we can perform these operations to manage your database records efficiently.
Create: Inserting Data
To insert data into a database, we use the INSERT SQL statement.
1 2 3 4 5 6 7 8 |
String insertQuery = "INSERT INTO users (id, name, email) VALUES (?, ?, ?)"; try (PreparedStatement stmt = connection.prepareStatement(insertQuery)) { stmt.setInt(1, 1); stmt.setString(2, "John Doe"); stmt.setString(3, "john.doe@example.com"); int rowsAffected = stmt.executeUpdate(); System.out.println("Rows inserted: " + rowsAffected); } |
Read: Retrieving Data
To retrieve data, we use the SELECT SQL statement. We can use ResultSet
to fetch the data from the result set.
1 2 3 4 5 6 7 8 9 |
String selectQuery = "SELECT * FROM users"; try (Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(selectQuery)) { while (rs.next()) { System.out.println("ID: " + rs.getInt("id")); System.out.println("Name: " + rs.getString("name")); System.out.println("Email: " + rs.getString("email")); } } |
Update: Modifying Data
To update existing records, the UPDATE SQL statement is used.
1 2 3 4 5 6 7 |
String updateQuery = "UPDATE users SET email = ? WHERE id = ?"; try (PreparedStatement stmt = connection.prepareStatement(updateQuery)) { stmt.setString(1, "newemail@example.com"); stmt.setInt(2, 1); int rowsAffected = stmt.executeUpdate(); System.out.println("Rows updated: " + rowsAffected); } |
Delete: Removing Data
To delete data, we use the DELETE SQL statement.
1 2 3 4 5 6 |
String deleteQuery = "DELETE FROM users WHERE id = ?"; try (PreparedStatement stmt = connection.prepareStatement(deleteQuery)) { stmt.setInt(1, 1); int rowsAffected = stmt.executeUpdate(); System.out.println("Rows deleted: " + rowsAffected); } |