JDBC 在使用 MySQL 控制台执行更新查询时抛出 SQLSyntaxErrorException

JDBC throws SQLSyntaxErrorException while executing UPDATE query while the query works using MySQL console

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

 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';

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

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

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

这不起作用。您不能将字符串常量值用作赋值 * 的左侧。当我在我的本地 MySQL 客户端测试它时,我得到这个错误:

ERROR 1064 (42000): 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' = 'new name' WHERE 's_id' = '6'' at line 1

错误报告在 's_name' 混淆了,因为引用的字符串文字在 UPDATE 语句中的那个位置无效。

WHERE 子句也是一个问题。这不是语法错误,但它没有按照您的预期执行。

WHERE 's_id' = '6';

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


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