如何解决使用 Python 在 mysql 中插入时,出现“字段列表中的未知列”错误
在尝试通过 python 脚本在 MysqL 中插入查询时,我面临一个错误,如“1054 (42S22):‘字段列表’中的未知列‘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)"
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。