2014-01-18 80 views
3

這是整條消息我收到:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException插入MySQL錯誤

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

這是代碼:

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

任何想法?

回答

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注入,如果你想知道更多)

+0

我得到了同樣的信息再次! :/ – pap

+0

嘗試從您的列名稱中刪除',這有幫助嗎? – kmera

+0

您在聲明結尾處忘記了分號。 – jmsalcido

相關問題