【问题标题】:JDBC throws SQLSyntaxErrorException while executing UPDATE query while the query works using MySQL console [duplicate]JDBC在执行UPDATE查询时抛出SQLSyntaxErrorException,而查询使用MySQL控制台工作[重复]
【发布时间】:2021-12-24 05:45:53
【问题描述】:

我正在编写一个学生管理应用程序并创建了一个更新学生数据的功能-

 public static void updateStudent(int id, int input) throws SQLException {
    Scanner sc = new Scanner(System.in);   //Scanner object
    Connection connection = ConnectionSetup.CreateConnection();  //Setting up connection
    String updateStatement = "UPDATE student_details SET ? = ? WHERE 's_id' = ?;"; //Initializing query
    PreparedStatement pstmt = connection.prepareStatement(updateStatement);

    System.out.println("Enter new name: ");
    String newName = sc.nextLine();
    pstmt.setString(1,"s_name"); //sets first ? to the columnname
    pstmt.setString(2,newName); //sets the second ? to new name
    pstmt.setString(3, String.valueOf(id));  //sets the third ? to the student ID
    pstmt.execute(); //executes the query

所有其他 CRUD 功能都可以正常工作,但是输入所有信息后,这个会引发以下错误-

Exception in thread "main" java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''s_name' = 'Prateek' WHERE 's_id' = '6'' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.execute(ClientPreparedStatement.java:371)
at com.Student.manage.StudentFunc.updateStudent(StudentFunc.java:76)
at Start.main(Start.java:58)

我尝试打印最终的查询,它具有正确的语法并且可以在 MySQL 控制台中运行-

SQL Query is: UPDATE student_details SET 's_name' = 'new name' WHERE 's_id' = '6';

这里的错误是什么?请帮我理解。

【问题讨论】:

  • 我也遇到了类似的问题,也在寻找解决方案。

标签: java mysql sql jdbc


【解决方案1】:

您不能对列名(或任何其他标识符或 SQL 关键字等)使用查询参数。当您使用查询参数时,它被解释为一个常量值。所以你的 UPDATE 语句就像你这样写一样执行:

UPDATE student_details SET 's_name' = 'new name' WHERE 's_id' = '6';

这不起作用。您不能将字符串常量值用作赋值的左侧*。当我在本地 MySQL 客户端中对其进行测试时,出现此错误:

ERROR 1064 (42000):您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 ''s_name' = 'new name' WHERE 's_id' = '6'' 附近使用正确的语法

错误报告它在's_name' 处感到困惑,因为引用的字符串文字在 UPDATE 语句中的该位置无效。

WHERE 子句也是一个问题。这不是语法错误,但它并没有达到您的预期。

WHERE 's_id' = '6';

这会将 字符串值 's_id' 与字符串值 '6' 进行比较,它不会将列 s_id 与值进行比较。显然字符串's_id' 不等于'6',因此条件将始终评估为假,并且不会更新任何行。


* 在大多数其他编程语言中,您也不能将常量值放在赋值的左侧。

【讨论】:

  • 除此之外,分号不是必需的,在使用查询控制台以外的任何内容时通常应省略分号
  • @Felix,你说得对,它不是必需的,但这不是这个问题中语法错误的原因。
  • 嘿,谢谢你帮助我。有没有办法在命名查询中将列名作为参数发送?还是我必须为所有不同的列(如 s_phone、s_number、s_age、s_city 等)编写不同的查询?
  • 必须在 SQL 查询中固定列名,然后才能将其作为参数传递给 connection.prepareStatement()。您可以使用字符串连接技术或StringBuilder 构建字符串。
猜你喜欢
  • 2021-05-05
  • 1970-01-01
  • 2023-03-25
  • 2012-12-06
  • 2011-06-07
  • 2011-10-17
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
相关资源
最近更新 更多