Python sqlite3:使用传递的参数和当前字段值的总和更新所有记录

Python sqlite3:使用传递的参数和当前字段值的总和更新所有记录

尝试使用每个现有字段值加上传递的参数的总和来更新所有记录。如果记录 A 中的字段 = 4 且记录 B = 5,我想更新所有记录,因此 A = 4 + X 和 B = 5 + X。这样,我可以快速将所有记录值增加给定数字 (X)。到目前为止,我还不知道如何让更新语句扩展传递的参数。

我可以用这行代码添加硬编码值:c.execute("UPDATE level SET sell = sell + 1;")下面的代码按原样工作。但是当我尝试用这行代码传递一个值update_sell(1)def update_sell(margin):像这样引用传递的值时,c.execute("UPDATE level SET sell = sell + margin;")它失败了。我在这里遗漏了什么?

这里完全是 Python 菜鸟。

要运行的脚本:

#MainScript.py
import sqlite3
from LevelClass import level

conn = sqlite3.connect(':memory:')
c = conn.cursor()

c.execute("""CREATE TABLE level (
            buy integer,
            sell integer,
            quan integer
            )""")

def insert_level(level):
    with conn:
        c.execute("INSERT INTO level VALUES (:buy, :sell, :quan)", {'buy': level.buy, 'sell': level.sell, 'quan': level.quan})

def get_level_by_sell(sell):
    c.execute("SELECT * FROM level WHERE sell=:sell", {'sell': sell})
    return c.fetchall()

def update_sell(margin):
    with conn:
        # below works with "sell + 1", but fails with "sell + margin"
        c.execute("UPDATE level SET sell = sell + 1;")

trans_1 = level(1, 5, 50)
trans_2 = level(2, 10, 60)

insert_level(trans_1)
insert_level(trans_2)

# value to pass to update_sell as var "margin"
update_sell(1)

find = get_level_by_sell(6)
print(find)

find = get_level_by_sell(11)
print(find)

conn.close()

班级:

# saved as LevelClass.py
class level:
    def __init__(self, buy, sell, quan):
        self.buy = buy
        self.sell = sell
        self.quan = quan

    def __repr__(self):
        return "Level('{}', '{}', {})".format(self.buy, self.sell, self.quan)

答案1

我认为您忘记了:更新函数。这对我来说有用。

def update_sell(margin):
    with conn:
        # below works with "sell + 1", but fails with "sell + margin"
        #c.execute("UPDATE level SET sell = sell + 1")
        c.execute("UPDATE level SET sell = sell + :margin", {"margin":margin})

相关内容