【发布时间】:2022-01-22 14:38:31
【问题描述】:
在下面的示例中,有两个数据帧 df 和 df1。我还有一个带有两个表的 MySQL 数据库。 Tables1 和 Table2,都和 df 有相同的列。
我想做的是:
- 使用 df1 在 table1 中找到正确的行,
- 将行移动到 table2 并更新列 'REMOVED'(从 False 到 True)和 'REMOVED_DATE(从 None 到 '2022-01-10)。
- 从 table1 中删除行
在你下面看到我的努力。但它不起作用,我可以想象有更好的解决方案可用。任何帮助将不胜感激。
df=pd.DataFrame({'ID':[25, 10],
'DATE':['2021-11-13', '2021-12-03'],
'LOC': ['NY', 'ML'],
'MAIL':['person1@gmail.com', 'person2@gmail.com'],
'NR': ['100000', '200000'],
'REMOVED': [False, False],
'REMOVED_DATE':[None,None]})
df1=pd.DataFrame({'ID':[25],
'REMOVED':[True],
'REMOVED_DATE':['2022-01-11']})
cols = "`,`".join([str(i) for i in df.columns.tolist()]) #use df to mirror the columns in the tables in the database.
for i, row in df1.iterrows():
id=row['ID']
sql=f"SELECT ID FROM table1 WHERE id={id}" # Check if ID is in table1.
cursor.execute(sql)
z=cursor.fetchall()
if not z:
print('insert') # if not, move on.
else: #If ID in, update, move and delete
sql=f"""UPDATE table1 SET (`" +cols + "`) VALUES (" + "%s,"*(len(row)-1) + "%s) WHERE id={id}""" # Update the whole row where ID match.
cursor.execute(sql, tuple(row))
mydb.commit()
sql=f"""INSERT INTO table2 SELECT * FROM table1 WHERE id={id}""" #insert it into table2
cursor.execute(str(sql), tuple(row))
mydb.commit()
sql=f"""DELETE from table1 WHERE id={id}""" # Delete it from table1
cursor.execute(sql)
mydb.commit()
【问题讨论】:
-
您在
cursor.execute()中缺少UPDATE语句的参数。 -
如果要删除行,为什么要更新 table1?
-
更好的解决方案或许是先将其移动到 table2 然后更新它?