-1

我正在尝试使用 Netbeans 更新表中的字段。更新声明如下:

String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/student_reg"; 
try { 
Class.forName(driver); 
Connection con = DriverManager.getConnection(url,"user","abc"); 
PreparedStatement state = con.prepareStatement("UPDATE supplier SET sname='" + txtname.getText()+"' , add='"+txtadd.getText()+"' WHERE sid ='" +txtid.getText() + "'"); 
state.executeUpdate(); 
JOptionPane.showMessageDialog(null, "Your Record sucessfully Updated"); 
}catch (Exception ex) { 
JOptionPane.showMessageDialog(null, ex);
}

但我收到以下错误:

com.mysql.jdbc.exceptions.jdbc4.MySQL SyntaxErrorException

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 'add=kegalle'where sid=001" 附近使用正确的语法

我该如何解决?

4

2 回答 2

2

您需要像反引号一样转义MySQL 中的保留字add

UPDATE supplier 
SET sname='" + txtname.getText()+"', `add` = ...
                 here ---------------^---^ 

顺便说一句,您没有正确使用准备好的语句。

于 2013-08-09T14:05:34.077 回答
1

The problem seems to be the way you're using PreparedStatement. Try this:

PreparedStatement state = con.prepareStatement("UPDATE supplier SET sname = ?, add = ? WHERE sid = ?");
state.setString(1,txtname.getText()); // sname (parameter 1)
state.setString(2,txtadd.getText()); // add (parameter 2)
state.setString(3,txtid.getText()); //sid (parameter 3) is actually a varchar?
state.executeUpdate(); 
于 2013-08-09T18:11:17.420 回答