Python执行MySQL SQL语句遇OperationalError错误的排查与解决
问题:Python执行MySQL插入语句时出现OperationalError(1054)
我在Visual Studio Code的Python环境中尝试运行SQL语句,查询MySQL Workbench 8.0中的数据库。程序连接数据库正常,但执行SQL部分时出错。
代码:
from gettext import install import pymysql con = pymysql.Connect( #Creating connection host = 'localhost', # port = 3306, # user = 'root', # password = 'Musa2014', # db = 'referees', # charset = 'utf8' # ) Ref_Info = input("Enter referee details: ") #First input statement Ref_First_Name, Ref_Last_Name, Ref_Level = Ref_Info.split() Ref_Info_Table = [] RefID = 1 #Setting the value of the RefID while Ref_Info != '': #Creating loop to get referee information Ref_Info = Ref_Info.split() Ref_Info.insert(0, int(RefID)) Ref_Info_Table.append(Ref_Info) #Updating Ref_Info_Table with new referee data print(Ref_Info_Table) #Printing values # print(Ref_Info) # print('Referee ID:', RefID) # print('Referee First Name:', Ref_First_Name) # print('Referee Last Name:', Ref_Last_Name) # print('Referee Level:', Ref_Level) # Ref_First_Name = Ref_Info[1] Ref_Last_Name = Ref_Info[2] Ref_Level = Ref_Info[3] RefID = RefID + 1 #Increasing the value of RefID Ref_Info = input("Enter referee details: ") #Establishing recurring input again cur = con.cursor() sql_query1 = 'INSERT INTO ref_info VALUES(1, MuhammadMahd, Ansari, B&W)' sql_query2 = 'SELECT * FROM ref_info' cur.execute(sql_query1) cur.execute(sql_query2) data = cur.fetchall() con.commit() cur.close() con.close()
错误信息:
Exception has occurred: OperationalError
(1054, "Unknown column 'MuhammadMahd' in 'field list'")
File "C:\Users\mahd_.vscode\Code Folders\Testing\test2.py", line 44, in
cur.execute(sql_query1)
错误原因
MySQL将插入语句中的MuhammadMahd、Ansari、B&W识别为列名而非字符串值——SQL语法规定,字符串类型的字段值必须用单引号(或双引号)包裹,否则数据库会默认将其解析为列名。而你的ref_info表中不存在名为MuhammadMahd的列,因此触发1054错误。
另外,你前面通过循环收集了裁判信息到Ref_Info_Table,但最终执行的INSERT语句是硬编码的固定值,并未使用收集到的数据,这也是逻辑疏漏。
解决方法
1. 修正硬编码INSERT语句(临时方案)
给所有字符串值加上单引号:
sql_query1 = "INSERT INTO ref_info VALUES(1, 'MuhammadMahd', 'Ansari', 'B&W')"
2. 推荐方案:参数化查询+批量插入收集的数据
直接拼接SQL字符串存在SQL注入风险,且容易出现格式错误,推荐使用pymysql的参数化查询,自动处理字符串包裹和特殊字符转义,同时批量插入你收集的所有裁判数据:
# 替换原代码中cur.execute及后续部分 cur = con.cursor() # 使用参数化占位符%s,批量插入收集到的裁判数据 sql_insert = "INSERT INTO ref_info VALUES(%s, %s, %s, %s)" cur.executemany(sql_insert, Ref_Info_Table) # 查询并打印结果 sql_query2 = "SELECT * FROM ref_info" cur.execute(sql_query2) data = cur.fetchall() for row in data: print(row) con.commit() cur.close() con.close()
参数化查询的优势:
- 自动处理字符串的单引号包裹,避免1054这类语法错误
- 自动转义特殊字符(如
B&W中的&),避免SQL语法异常 - 杜绝SQL注入风险,提升代码安全性
内容的提问来源于stack exchange,提问作者Muhammad
相关产品推荐
相关产品推荐

