【问题标题】:While doing insertion in mysql using Python , getting an error as "Unknown Column in field list"使用 Python 在 mysql 中进行插入时,出现“字段列表中的未知列”错误
【发布时间】:2021-04-11 20:59:24
【问题描述】:

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

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

【问题讨论】:

  • 打印您的 sql 查询字符串并将其添加到问题中
  • @rdas - 我已经在上面更新了。如果我是对的,这就是你让我展示的东西。
  • 值列表中的值没有被引用(对于字符串)
  • 如果我引用这些值,那么它也会引发错误。无论如何我得到了解决方案谢谢

标签: python mysql database mysql-python


【解决方案1】:

您应该添加占位符并将实际值作为params 传递给execute 方法,而不是手动格式化INSERT 语句:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2013-01-26
    • 1970-01-01
    相关资源
    最近更新 更多