4

This is the whole message I receive:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user','age','school','password') values ('Admin','22','tei','admin')' at line 1

And this is the code:

String user = textField.getText().trim();
String age = textField_3.getText().trim();
String school = textField_4.getText().trim();
String password = String.valueOf(passwordField.getPassword());
String password1 = String.valueOf(passwordField_1.getPassword());

if(password.equals(password1)){


Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","1234");
PreparedStatement st = con.prepareStatement("insert into user ('user','age','school','password') values ('"+user+"','"+age+"','"+school+"','"+password+"')");
int rs = st.executeUpdate();

JOptionPane.showMessageDialog(frame, "Data Saved Successfully");

Any ideas?

1 Answer 1

5

The point of prepared statements is, among others, to not concatenate your queries yourself.

You want to do the following:

//first you "prepare" your statement (where the '?' acts as a kind of placeholder)
PreparedStatement st = con.prepareStatement("insert into user (user,age,school,password) values (?,?,?,?);");
//now you bind the data to your parameters
st.setString(1, user);
...
//and then you can execute it
st.executeUpdate()

For more details see the official tutorial.

There are a couple of things happening behind the scenes that make the query safe, like escaping special characters that would otherwise allow altering the statement (google SQL injections if you want to know more)

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

9 Comments

I get the same message again! :/
try to remove the ' from your column names, does that help?
you are forgetting the semicolon at the end of the statement.
Now I am getting another error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'user' in 'field list'
I found it! Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","1234"); PreparedStatement st = (PreparedStatement) con.prepareStatement("INSERT INTO user (username,age,school,password) VALUES (?,?,?,?)"); st.setString(1, user); st.setString(2, age); st.setString(3, school); st.setString(4, password); st.executeUpdate(); st.close(); con.close();
|

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.