我正在编写一个学生管理应用程序,并创建了一个更新学生数据的功能-
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,并且不会更新任何行。
* 在大多数其他编程语言中,您也不能将常量值放在赋值的左侧。
关于java - 当查询使用 MySQL 控制台运行时,执行 UPDATE 查询时 JDBC 抛出 SQLSyntaxErrorException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69933401/