首页 文章

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

提问于
浏览
4

这是我收到的全部信息:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL语法中有错误;查看与您的MySQL服务器版本对应的手册,以便在''user','age','school','password')值附近使用正确的语法('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 回答

  • 4

    除其他外,准备好的陈述的要点是不要自己连接您的查询 .

    您想要执行以下操作:

    //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注入)

相关问题