根据if语句更改方法中的查询

2024-09-28 20:18:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在从事一个Python项目,在这个项目中,我需要使用REPLACE-into查询。该表用于预算,应该根据值更新支出或收入列

我的想法是,在初始的if声明中检查它是费用还是收入。然后,查询列名“TYPE”应该根据if语句进行更改。至少和往常一样,我将把这些值格式化到查询中执行

如何根据if语句正确设置查询的格式

PYTHON:

for key, value in budget.items():
    if value > 0:
        type = "incomes"
    else:
        type = "expenses"
        
    updateQuery = """
        REPLACE into budget (
            username,
            {type},
            categories
        ) VALUES ('{}', '{}', '{}');
    """.format(username, type, key)

    insertTuple = (username, value)
    cursor.execute(updateQuery, insertTuple)

    self.__dbConnector.commit()

M$SQL

CREATE TABLE budget (
    budget_id VARCHAR(255),
    incomes MONEY,
    expense MONEY,
    savings MONEY,
    investments MONEY,
    categories VARCHAR(255),
    FOREIGN KEY(budget_id) REFERENCES user (username)
);

Tags: 项目keyifvaluetypeusername语句replace
1条回答
网友
1楼 · 发布于 2024-09-28 20:18:24

可以使用f字符串将type的值替换为SQL

使用%s作为将由cursor.execute()inserType填充的占位符。格式化SQL时不需要填写它们

for key, value in budget.items():
    if value > 0:
        type = "incomes"
    else:
        type = "expenses"
        
    updateQuery = f"""
        REPLACE into budget (
            username,
            {type},
            categories
        ) VALUES (%s, %s, %s);
    """

    insertTuple = (username, value, key)
    cursor.execute(updateQuery, insertTuple)

    self.__dbConnector.commit()

相关问题 更多 >