Mark As Completed Discussion

CRUD Operations

CRUD stands for Create, Read, Update, and Delete, which are the basic operations performed on data stored in a database. These operations are the foundation of any database-driven application. Let's explore each operation in detail:

  • Create: Create operation is used to add new data to the database. In the context of a web application, this operation is often performed when a user submits a form or sends a request to the server. For example, a user registration form can be used to create a new user in the database.

  • Read: Read operation is used to retrieve data from the database. This operation is performed when a user wants to view or access the stored data. In the context of a web application, this operation is commonly used to display information on web pages. For example, fetching a list of users from a database and displaying them on a web page.

  • Update: Update operation is used to modify existing data in the database. This operation is typically performed when a user wants to update their information or make changes to an existing record. For example, editing a user profile and saving the updated details to the database.

  • Delete: Delete operation is used to remove data from the database. This operation is performed when a user wants to delete a record or entity from the database. For example, deleting a user account from the system.

CRUD operations are essential in building applications that interact with databases. By understanding these operations, you will be able to perform basic data manipulation and work with the database effectively in your applications.

TEXT/X-JAVA
1// Replace with a Java Spring Boot example that demonstrates CRUD operations on a MySQL database
2@GetMapping("/users")
3public List<User> getAllUsers() {
4    return userRepository.findAll();
5}
6
7@PostMapping("/users")
8public User createUser(@RequestBody User user) {
9    return userRepository.save(user);
10}
11
12@PutMapping("/users/{id}")
13public User updateUser(@PathVariable(value = "id") Long userId, @RequestBody User userDetails) {
14    User user = userRepository.findById(userId)
15            .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + userId));
16    
17    user.setName(userDetails.getName());
18    user.setEmail(userDetails.getEmail());
19    
20    return userRepository.save(user);
21}
22
23@DeleteMapping("/users/{id}")
24public ResponseEntity<?> deleteUser(@PathVariable(value = "id") Long userId) {
25    User user = userRepository.findById(userId)
26            .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + userId));
27    
28    userRepository.delete(user);
29    return ResponseEntity.ok().build();
30}```
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment