我目前正在从事一个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)
);
可以使用f字符串将
type
的值替换为SQL使用
%s
作为将由cursor.execute()
从inserType
填充的占位符。格式化SQL时不需要填写它们相关问题 更多 >
编程相关推荐