ERROR =(java.sql.SQL.SyntaxErrorException:您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以在'?,Last_Name = ?、 Contact =?附近使用正确的语法。第1行的Email_ID =?WHERE用户名= aman036'
我是编程的初学者,所以将不胜感激。这是我的代码:-
Connection Con=null;
PreparedStatement pst=null;
ResultSet rs=null;
String query="UPDATE cashier SET First_Name=?, Last_Name=?, Contact=?, Email_ID=? WHERE Username=?";
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Con=DriverManager.getConnection("jdbc:mysql://localhost/billing","Aman","Amanbhattt");
pst=Con.prepareStatement(query);
pst.setString(1,NameField.getText());
pst.setString(2,LastNameField.getText());
pst.setString(3,ContactField.getText());
pst.setString(4,EmailField.getText());
pst.setString(5,UsernameField.getText());
pst.executeUpdate(query);
JOptionPane.showMessageDialog(null,"Data Updated Successfully");
Con.close();
@ Aman
我没有得到您的全部错误,但是从您的代码中我确定您没有在代码中处理sql特殊字符。您需要为SQL查询添加转义字符。
MySQL server version for the right syntax to use near '?, Last_Name=?, Contact=?, Email_ID=? WHERE Username=aman036'
在您的错误消息中,我可以看到用户名后带有单引号aman036',因此您需要删除该用户名。
请使用以下代码删除SQL查询字符串中的特殊字符
public String escapeMetaCharacters(String inputString){
final String[] metaCharacters = {"\\","^","$","{","}","[","]","(",")",".","*","+","?","|","<",">","-","&","%"};
for (int i = 0 ; i < metaCharacters.length ; i++){
if(inputString.contains(metaCharacters[i])){
inputString = inputString.replace(metaCharacters[i],"\\"+metaCharacters[i]);
}
}
return inputString;
}
String query="UPDATE cashier SET First_Name=?, Last_Name=?, Contact=?, Email_ID=? WHERE Username=?";
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Con=DriverManager.getConnection("jdbc:mysql://localhost/billing","Aman","Amanbhattt");
pst=Con.prepareStatement(query);
pst.setString(1,escapeMetaCharacters(NameField.getText()));
pst.setString(2,escapeMetaCharacters(LastNameField.getText()));
pst.setString(3,escapeMetaCharacters(ContactField.getText()));
pst.setString(4,escapeMetaCharacters(EmailField.getText()));
pst.setString(5,escapeMetaCharacters(UsernameField.getText()));
pst.executeUpdate(query);
JOptionPane.showMessageDialog(null,"Data Updated Successfully");
Con.close();
我知道准备好的语句不需要特殊字符处理。但是有时它也发生在准备好的语句中。因此,请尝试此操作,并让我知道问题是否已解决
我希望它能帮助您谢谢