skip to Main Content

I have this code snippet which will delete all rows in the user_interests table. I have a parameter of int id which is user id. I want to pass this parameter to my SQL statement. I have tried using ".... user_id = @id" but it wont work when I run it on Postman. I also tried using static value for is "... user_id = 1" and it is working fine.

public boolean deleteInterest(int id) {
        boolean isDeleted = false;
        String sql = "DELETE FROM user_interests WHERE user_id = @id" ;
        
        if(userRepository.findById(id) != null) {
            dbTemplate.execute(sql);
            isDeleted = true;
        }
        
        return isDeleted;
    }

How can I pass the id parameter to my sql statement?

2

Answers


  1. You can pass the I’d parameter like below as this is very basic.

    String sql = "DELETE FROM user_interests WHERE user_id = " + id
    

    This will work fine but it has a risk of SQL injection so you should set the parameters using prepared statements.

    Login or Signup to reply.
  2. String sql = "DELETE FROM user_interests WHERE user_id = '"+parameterName+"'";
    

    You can pass the parameter in sql query like this

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search