我在尝试迭代地在MySQL表中插入值时遇到错误。我不确定insert语句是否正确?或者我们有更好的方法在我的表格中插入值。
mysql.connector.errors.ProgrammingError:1064(42000):您的SQL语法出错;
import mysql.connector
from collections import defaultdict
cnx = mysql.connector.connect(user='root', password='hadoop',
host='localhost',
database='test')
lines = defaultdict(dict)
with open("test.txt") as f:
for line in f:
parts = line.split()
key = tuple(parts[1:3]) # unique key with servername and datetime
lines[key][parts[0]] = parts[3]
lines[key]["servername"] = parts[2]
lines[key]["datetime"] = parts[1]
res = list(lines.values())
try:
cursor = cnx.cursor()
for index in range(len(res)):
cursor.execute("""
insert into cpu_util_all (servername,date_time,cpu_number,cpu_user,cpu_nice,cpu_system,cpu_wait,cpu_idle) values ('%s', '%s', '%s', '%s','%s', '%s', '%s', '%s') % (res[index]["servername"],res[index]["datetime"],res[index]["cpunumber"],res[index]["cpuuser"],res[index]["cpunice"],res[index]["cpusystem"],res[index]["cpuwait"],res[index]["cpudile"])
""")
cnx.commit()
cursor.close()
finally:
cnx.close()
print("Inserted successfully")
答案 0 :(得分:1)
问题是你正在尝试在查询本身中进行字符串替换。此外,您应该允许MySQLdb为您解析参数值,例如:
cursor.execute("""
insert into cpu_util_all
(servername,date_time,cpu_number,cpu_user,
cpu_nice,cpu_system,cpu_wait,cpu_idle)
values (%s, %s, %s, %s, %s, %s, %s, %s)""",
(res[index]["servername"],res[index]["datetime"],
res[index]["cpunumber"],res[index]["cpuuser"],
res[index]["cpunice"],res[index]["cpusystem"],
res[index]["cpuwait"],res[index]["cpudile"]
)
)