[英]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):您的 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',因此條件將始終評估為 false,並且不會更新任何行。
*在大多數其他編程語言中,您也不能在賦值的左側放置常量值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.