Anthony Mead
Anthony Mead

Reputation: 33

hibernate query wont work with user input

hi there i have a hibernate project which im trying to delete an entry from. code looks like this.

import csc1035.hibernate.HibernateUtil;
import org.hibernate.Session;

import java.util.Scanner;

public class Main {

    public static void main(String[]args){

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Scanner scanner = new Scanner(System.in);
        System.out.println("Which entry would you like to delete? ");

        String user_input = scanner.nextLine();

        session.createQuery("delete from StudentEX1 where surname="+user_input).executeUpdate();

        session.getTransaction().commit();
        session.close();
    }

}

it runs fine and deletes the row when i change remove the user_input parameter from the query, and replace it with a string i.e session.createQuery("delete from StudentEX1 where surname="'Two'").executeUpdate();, but using user_input variable gives me the error. e.g, im testing the user_input by entering surname "Three", the error: Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'Three' in 'where clause'

I'm just a bit confused as it works fine when there is a normal string, but user input just doesnt seem to work? Note: java displays the query in the console but then goes on to give me an error.

Upvotes: 0

Views: 523

Answers (1)

Zeke Rogers
Zeke Rogers

Reputation: 146

You should never pass user-supplied values directly into a query. Instead, pass parameters. I also suspect you might be wanting a native query here in which case use createNativeQuery instead.

Example:

Query query = session.createNativeQuery("delete from StudentEX1 where surname = ?");
query.setParameter(1, user_input);
query.executeUpdate();

I also suggest using camelCase for variable names, ie userInput.

Upvotes: 1

Related Questions