5

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

当我只更新名字 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();
      }
   }
}

列名是正确的。仅更新自己的姓氏也可以正常工作。尝试同时执行这两种操作时,更新失败并出现语法错误,如注释掉的行。

4

1 回答 1

10

3个问题:

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

更正后的语法:

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

SQL 参考

于 2013-04-04T23:15:18.857 回答