com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException插入mysql错误

时间:2014-01-18 16:57:46

标签: java mysql jdbc

这是我收到的全部信息:

  

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL语法中有错误;查看与您的MySQL服务器版本相对应的手册,以便在“用户”,“年龄”,“学校”,“密码”)值附近使用正确的语法('Admin','22','tei','admin ')'第1行

这是代码:

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");

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

准备好的陈述的重点是,不要自己连接你的问题。

您想要执行以下操作:

//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()

有关详细信息,请参阅the official tutorial

幕后发生了一些使查询安全的事情,比如转义特殊字符,否则会改变声明(如果你想了解更多的话,谷歌SQL注入)