Java com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException 插入mysql错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21207049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException Insert mysql error
提问by pap
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
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在 ''user','age','school','password') 值 ('Admin','22','tei','admin 附近使用的正确语法')' 在第 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?
有任何想法吗?
采纳答案by kmera
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)
幕后发生的一些事情使查询安全,例如转义特殊字符,否则会允许更改语句(如果您想了解更多信息,请使用谷歌 SQL 注入)