【问题标题】:Whilw Updating the data using Python in MYSql , getting an error在 MYSql 中使用 Python 更新数据时,出现错误
【发布时间】:2023-03-22 10:38:01
【问题描述】:

我知道有一些语法错误,但无法找到它。我确保它被插入到正确的表中。

column_update = input("Enter the column name where Data has to be updated: ")
update_data = input("Enter the new value: ")
column_name = input("Enter the column to get the row: ")
row_value = input("Enter the row value: ")

try:
    sql_update_query = """ UPDATE EmployeeList SET %s = %s WHERE %s = %s """
    my_cursor.execute(sql_update_query,params = (column_update,update_data,column_name,row_value))
    mydb.commit()
    print("Record Updated Successfully")

except mysql.connector.Error as error:
    print("Failed to update record to database: {}".format(error))

finally:
    if (mydb.is_connected()):
        my_cursor.close()
        mydb.close()
        print("MySQL connection is closed")

我的桌子:

my_cursor.execute("CREATE TABLE IF NOT EXISTS EmployeeList(user_id INT AUTO_INCREMENT PRIMARY KEY,EMPID INT, Emp_Name VARCHAR(100),Designation VARCHAR(100), Role VARCHAR(100), Updated_by VARCHAR(100), LastUpdate TIMESTAMP DEFAULT NOW())")

运行脚本后必须提供用户输入详细信息。

Enter the column name where Data has to be updated: Role
Enter the new value: Software
Enter the column name to get the row: EMPID
Enter the column value: 1

错误:

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 ''Role' = 'Software' WHERE 'EMPID' = '1'' at line 1

【问题讨论】:

  • EMPID 是一个整数,因此在将其作为参数传递给execute 之前,您可能必须将其转换为int,如下所示:if column_name == "EMPID": row_value = int(row_value)
  • 不,添加 "if column_name == "EMPID": row_value = int(row_value)" 时不起作用。我也尝试使用其他列执行数据,它显示相同的错误。“1064(42000):您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以获取在“角色”附近使用的正确语法' = 'Soft' WHERE 'Emp_Name' = 'Abhinav'' 在第 1 行"

标签: python mysql mysql-python


【解决方案1】:

sql_update_query = """ UPDATE EmployeeList SET %s = %s WHERE %s = %s;"""

最后添加一个分号(;),检查一次是否有效。

【讨论】:

  • 去检查输入的 EMPID 在您的表中是否可用。如果没有,先插入数据。
  • 它就在那里。当我尝试给出不同的条件时遇到同样的错误,即 Emp_Name
  • 您是否先输入数据。您正在更新的数据必须存在于表中。 Like- 5 12 Abhinav 工程师 昨天今天等高级工程师 然后访问 empid = 12 并更新它。
猜你喜欢
  • 2018-09-27
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
相关资源
最近更新 更多