【问题标题】:Java mysql, Simple update with PreparedStatement has syntax errorJava mysql,使用 PreparedStatement 进行简单更新有语法错误
【发布时间】:2013-03-27 05:45:26
【问题描述】:

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

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

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

【问题讨论】:

  • 我认为问题是“,”你必须把它放在姓氏之前并删除第二组

标签: java mysql sql-update prepared-statement syntax-error


【解决方案1】:

3 个问题:

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

更正的语法:

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

SQL Reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 2015-09-12
    • 2012-11-05
    • 1970-01-01
    相关资源
    最近更新 更多