To change SQL from command line to POST method in SpringBoot, you need to follow these steps:
Example - The following code snippet demonstrates how to change SQL from command line to POST method in SpringBoot:
@RestController
public class MyController {
private JdbcTemplate jdbcTemplate;
@Autowired
public MyController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@PostMapping("/users")
public ResponseEntity<String> createUser(@RequestBody User user) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
int rows = jdbcTemplate.update(sql, user.getName(), user.getEmail());
if(rows > 0) {
return new ResponseEntity<>("User created successfully", HttpStatus.CREATED);
} else {
return new ResponseEntity<>("Failed to create user", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
This code receives a POST request to create a new user with the name and email, parses the request body to retrieve the user object, and executes an SQL query to insert the user into the database using the JdbcTemplate library. Finally, it returns a response with the appropriate status code and message indicating the success or failure of the query execution.
Asked: 2021-10-17 11:00:00 +0000
Seen: 15 times
Last updated: Jul 14 '21