我正在编写一个python脚本,该脚本从名为octopart的网站访问数据,并将该数据插入MySQL表中。最终目标是这样:
我已经包含了下面应该执行的代码(4.)。我仍然收到1062重复条目错误。有什么建议吗?
变量:
value ['display_value']:每个数据块要添加到mylistv的下一个值
heads = ','.join(str(i) for i in mylisth)
#create string input of %s corresponding to number of entries in mylisth
placelst = ['%s' for i in mylisth]
placestr = ','.join(str(i) for i in placelst)
#add_capacitor -> SQL query line // data_capacitor -> values to be inserted using query line
duplicate_check = ("SELECT * FROM capacitors")
add_capacitor = ("INSERT INTO capacitors ("+heads+") VALUES ("+placestr+")")
replace_capacitor = ("REPLACE INTO capacitors ("+heads+") VALUES ("+placestr+")")
data_capacitor = mylistv
cursor.execute(duplicate_check)
rows = cursor.fetchall()
for row in rows:
for col in row:
if col == value['display_value']:
cursor.execute(replace_capacitor, data_capacitor)
else:
cursor.execute(add_capacitor, data_capacitor)
emp_no = cursor.lastrowid
cnx.commit()
time.sleep(1)
答案 0 :(得分:1)
也许您应该使用INSERT ... ON DUPLICATE KEY UPDATE
。然后,您无需选择和重新处理表的每一行,而只需通过一次调用cursor.execute
插入该数据,并让MySQL引擎在存在重复键时处理更新:
heads = ','.join(str(i) for i in mylisth)
placelst = ['%s' for i in mylisth]
placestr = ','.join(str(i) for i in placelst)
replacestr = ', '.join(['{}=%s'.format(h) for h in mylisth])
sql = """INSERT INTO capacitors ({heads}) VALUES ({placestr})
ON DUPLICATE KEY UPDATE {replacestr}""".format(
heads=heads, placestr=placestr,
replacestr=replacestr)
for data_capacitor in larger_loop:
args = data_capacitor*2
cursor.execute(sql, args)