Tony
Tony

Reputation: 33

How to pass a parameter in SQL statement in Springboot

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?

Upvotes: 2

Views: 782

Answers (2)

Coder baaz
Coder baaz

Reputation: 1

String sql = "DELETE FROM user_interests WHERE user_id = '"+parameterName+"'";

You can pass the parameter in sql query like this

Upvotes: 0

Alien
Alien

Reputation: 15878

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.

Upvotes: 1

Related Questions