0

I have a listener that listens a button and takes 3 texts fields from input to execute an update query. I want to execute the update but in the query to pass my local variables(name,city,salary). What can i do this?

public void actionPerformed(ActionEvent arg0) {
        final String name;
        final String city;
        final String salary; 

        name = (textFieldName.getText());   
        city = (textFieldCity.getText());   
        salary = (textFieldSalary.getText());   

        System.out.println(salary);
        try {
                Statement s = connection.createStatement();
                s.executeUpdate("INSERT INTO users (name,city,salary) VALUES (name, city,salary)");

1 Answer 1

2

I'd go with a PreparedStatement

PreparedStatement s = connection.prepareStatement("INSERT INTO users (name,city,salary) VALUES (?, ?, ?)");
s.setString(1, name);
s.setString(2, city);
s.setString(3, salary);
boolean res = s.execute();

This approach is a bit better, quoting will be automatically managed and will prevent simple SQL Injection.

Sign up to request clarification or add additional context in comments.

2 Comments

@Saksoo glat it helped out. PreparedStatements are better for a many reasons, the most obvious is avoiding SQL Injection, remember, if the values you're passing to the query as parameter, come from some sort of user input, never trust them, and perform some validation on data.
i know thanks. I just didn't know how to use them but it seems that it is very simple now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.