【发布时间】: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';
这里的错误是什么?请帮我理解。
【问题讨论】:
-
我也遇到了类似的问题,也在寻找解决方案。