Java mysql,使用PreparedStatement进行简单更新时出现语法错误

use*_*069 4 java mysql syntax-error prepared-statement sql-update

此代码具有某种简单的语法错误.我已经打了好几个小时了,我放弃了.你能发现它吗?我打赌这很容易.谢谢!

当我更新John的第一个名字时,没问题.当我尝试更新姓氏的注释行时,语法错误.

import java.sql.*;

public class UpdateTester {

   public static void main(String[] args) {

      try {

         Connect connect = new Connect();
         Connection connection = connect.getConnection();

         try {

            String sql        = "UPDATE student SET firstName = ? "
                     + " WHERE studentID = 456987";

            //String sql     = "UPDATE student SET firstName = ? "
            //       + " Set lastName = ?, "
            //       + " WHERE studentID = 456987";

            PreparedStatement pst = connection.prepareStatement(sql);
            pst.setString(1, "John");

            //pst.setString(2, "Johnson");

            pst.executeUpdate();
            System.out.println("Updated Successfully!");

            connection.close();

         } catch (SQLException e) {
            System.out.println("Exception 1!");
            e.printStackTrace();
         }
      } catch (Exception e) {
         System.out.println("Exception 2!");
         e.printStackTrace();
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

列名是正确的.只更新它自己的姓氏也能正常工作.尝试同时执行这两项操作时更新失败并出现语法错误,如注释掉的行中所示.

Rei*_*eus 10

3个问题:

  • SET关键字只能在UPDATE语句中出现一次:
  • 逗号在第二个参数丢失之前
  • 在where子句之前不必要的逗号

更正后的语法:

String sql     = "UPDATE student SET firstName = ?, "
               + " lastName = ? "
               + " WHERE studentID = 456987";
Run Code Online (Sandbox Code Playgroud)

SQL参考