使用 python 和 Excel 中的数据更新插入到 MySQL。
我正在使用 python 填充 MySQL 数据库。
数据存储在 Excel 表格中。
因为DB是用来监控“项目”的,所以有可能出现重复pk的情况,所以在这种情况下需要更新而不是插入,因为一个项目可以有很多阶段。
此外,还有一个值要插入数据库表中,但无法从电子表格中添加。所以我想知道在这种情况下,该值的插入是否大部分是使用单独的查询来完成的,或者是否有办法将其插入到同一查询中。该值为供应商ID,需要插入到id_ops和cif_store之间。
最后,我需要执行内部联接,使用 store_cif 从另一个名为 store 的表导入 store_id。我知道怎么做,但我想知道它是否也必须从单独的查询中执行,或者可以在同一个查询中执行。
到目前为止,我已经做到了这一点。
import xlrd
import MySQLdb
def insert():
book = xlrd.open_workbook(r"C:\Users\DevEnviroment\Desktop\OPERACIONES.xlsx")
sheet = book.sheet_by_name("Sheet1")
database = MySQLdb.connect (host="localhost", user = "pytest", passwd = "password", db = "opstest1")
cursor = database.cursor()
query = """INSERT INTO operation (id_ops, cif_store, date, client,
time_resp, id_area_service) VALUES (%s, %s, %s, %s, %s, %s)"""
for r in range(1, sheet.nrows):
id_ops = sheet.cell(r,0).value
cif_store = sheet.cell(r,1).value
date = sheet.cell(r,2).value
client = sheet.cell(r,3).value
time_resp = sheet.cell(r,4).value
id_area_service = sheet.cell(r,5).value
values = (id_ops, cif_store, date, client, time_resp, id_area_service)
cursor.execute(query, values)
# Close the cursor
cursor.close()
# Commit the transaction
database.commit()
# Close the database connection
database.close()
# Print results
print ("")
print ("")
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print ("Imported", columns,"columns and", rows, "rows. All Done!")
insert()
最佳答案
您正在寻找的是 INSERT ... ON DUPLICATE KEY UPDATE ...
看这里https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
关于无关数据,如果它是所有行的静态值,您可以将其直接硬编码到 INSERT 查询中。如果它是动态的,您就必须编写一些额外的逻辑。
例如:
query = """INSERT INTO 操作(id_ops、hard_coded_value、cif_store、日期、客户端、
time_resp, id_area_service) VALUES (%s, "我的硬编码值", %s, %s, %s, %s, %s)"""
关于python - MySQL从Python插入/更新,来自Excel电子表格的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57789687/