Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading