简体   繁体   中英

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?

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.

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

You can pass the parameter in sql query like this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM