Python sqlite3:使用傳遞的參數和目前欄位值的總和更新所有記錄

Python sqlite3:使用傳遞的參數和目前欄位值的總和更新所有記錄

嘗試使用每個現有欄位值加上傳遞的參數的總和來更新所有記錄。如果記錄 A = 4 和記錄 B = 5 中的字段,我想更新所有記錄,因此 A = 4 + X 和 B = 5 + 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})

相關內容