【问题标题】:Can't get a query to execute in SQLAlchemy that's working in mySQL Workbench无法在 mySQL Workbench 中运行的 SQLAlchemy 中执行查询
【发布时间】: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


    【解决方案1】:

    您使用 connection.execute() 函数运行更新查询的方式可能存在问题。要执行 SQLAlchemy 查询,您需要在使用 text() 函数创建的文本对象上调用 connection.execute()。在您的代码中,您正在检查第一个查询的结果,但不执行您根据结果创建的更新或插入查询。

    尝试将 if 子句更改为:

    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)
    

    以及对此的 else 子句:

    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)
    

    此外,最好使用占位符而不是直接使用字符串格式来避免 SQL 注入攻击。

    【讨论】:

    • 感谢您的答复。你介意指出有什么不同吗?除非我遗漏了什么,否则它看起来与我拥有的代码相同?我只是尝试将其粘贴进去,但仍然得到相同的结果。
    猜你喜欢
    • 1970-01-01
    • 2011-10-09
    • 2012-07-21
    • 2020-07-06
    • 2023-02-16
    • 2021-03-09
    • 2020-09-04
    • 2017-01-11
    • 1970-01-01
    相关资源
    最近更新 更多