使用 Python 在 mysql 中插入时,出现 "Unknown Column in field list" 错误

While doing insertion in mysql using Python , getting an error as "Unknown Column in field list"

尝试通过 python 脚本在 MYSql 中插入查询时,我遇到错误“1054 (42S22):'field list' 中的未知列 'Abhinav' ”。有一些小的语法错误,但我找不到它。

my_cursor.execute("CREATE DATABASE IF NOT EXISTS task")
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())")
EMP_ID = input("Enter the Employement Id : ")
EmpName = input("Enter the Employee Name : ")
Designations = input("Enter the Designation : ")
Roles = input("Enter the Role : ")
Updatedby = input("Enter the name of the Person updated by: ") 
try:
    sql_insert_query = f"INSERT INTO EmployeeList(EMPID,Emp_Name,Designation,Role,Updated_by) VALUES ({EMP_ID},{EmpName},{Designations},{Roles},{Updatedby})"
    my_cursor.execute(sql_insert_query)
    mydb.commit()
    print("Record inserted 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")

用户输入的详细信息必须在 运行 脚本之后给出。

Enter the Employement Id : 1
Enter the Employee Name : Abhinav
Enter the Designation : Software Engineer
Enter the Role : GE
Enter the name of the Person updated by: Abhi

错误-

Failed to update record to database: 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 'Engineer,GE,Abhi)' at line 1
MySQL connection is closed

与其手动格式化 INSERT 语句,不如添加占位符并将实际值作为 params 传递给 execute 方法:

sql_insert_query = "INSERT INTO EmployeeList(EMPID,Emp_Name,Designation,Role,Updated_by) VALUES (%s,%s,%s,%s,%s)"
my_cursor.execute(sql_insert_query, params=(EMP_ID, EmpName, Designations, Roles, Updatedby))

这是一些文档:https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html