【发布时间】:2023-02-04 01:45:30
【问题描述】:
我有一个非常简单的代码块,旨在遍历 DataFrame 的行,以检查新数据的任何值是否与 SQL 表的相应值匹配。如果是这样,我运行 fetchone() 以获取 id,然后使用该 id 更新 SQL 中的现有行,否则它将所有数据作为新行插入。
我遇到的问题是 fetchone() 查询执行并返回正确的 id。但是,在 if 子句中,我无法执行该查询。代码编译并运行,但数据库中没有任何更新。
当我调试时,`查询变量在下面
query={TextClause}UPDATE projects SET Lead_MD='Stephen', Primary_Deal_Type='Debt', Secondary_Deal_Type='1', Start_Date='2022-06-01' WHERE id=2
我试过将该子句复制到 mySQL Workbench 中,它正确地更新了表,这让我更加困惑。任何帮助,将不胜感激! 这是我的代码:
from sqlalchemy import create_engine, text
from sqlupdate import data_frame_from_xlsx_range
df = data_frame_from_xlsx_range(fileloc,'projects_info')
user = 'root'
pw = 'test!*'
db = 'hcftest'
engine = create_engine("mysql+pymysql://{user}:{pw}@localhost:3306/{db}"
.format(user=user, pw=pw, db=db),
echo=True)
# Check if each row in the Excel data already exists in the MySQL table
connection = engine.connect()
for i, row in df.iterrows():
query = text("SELECT id FROM projects WHERE Project_Name='{}' and Client_Name='{}'".format(row["Project_Name"], row["Client_Name"]))
result = connection.execute(query).fetchone()
# If the row already exists, update the remaining columns with the Excel data
if result:
query = text("UPDATE projects SET Lead_MD='{}', Primary_Deal_Type='{}', Secondary_Deal_Type='{}', Start_Date='{}' WHERE id={}".format(row["Lead_MD"], row["Primary_Deal_Type"], row["Secondary_Deal_Type"], row["Start_Date"], result[0]))
connection.execute(query)
# If the row does not exist, insert the Excel data into the MySQL table
else:
query = text("INSERT INTO table_name (Project_Name, Client_Name, Lead_MD, Primary_Deal_Type, Secondary_Deal_Type, Start_Date) VALUES ('{}', '{}', '{}', '{}', '{}', '{}')".format(row["Project_Name"], row["Client_Name"], row["Lead_MD"], row["Primary_Deal_Type"], row["Secondary_Deal_Type"], row["Start_Date"]))
connection.execute(query)
connection.close()
【问题讨论】:
标签: python mysql sql sqlalchemy