【问题标题】:Loop through individual rows and update those rows SQLite3 Python循环遍历各个行并更新这些行 SQLite3 Python
【发布时间】:2017-08-24 06:44:18
【问题描述】:

我有下表:http://prntscr.com/gc9oat

我正在尝试更新 NOTIFIED 列,因为我循环遍历此表中名为 notifyTable 的行,条件为

if coinMarketValue > value and notified == 0:

这是我目前拥有的代码

connection = sqlite3.connect('notify.db')

c = connection.cursor()    
c.execute('SELECT * FROM notifyTable')
data = c.fetchall()


for row in data:
    authorID = row[1]
    coin = row[2]
    operator = row[3]
    value = row[4]
    coinMarketValue = row[5]
    notified = row[6]

    if operator == '<':           
        if coinMarketValue < value and notified == 0: #notified hasnt been set true 
            print("coin market value is less than value so updating notifed to True")             
            connection.execute("UPDATE notifyTable set notified = 'True' WHERE coinMarketValue < value AND notified == 0")
            connection.commit()

好的,现在代码遍历每一行,如果条件为真。

coinMarketValue < value AND notified == 0

然后它将所有 Notified 列更新为 True - 而不是仅更新当前行。

那么,我怎样才能只更新脚本当前正在处理的行上的通知(而不是更新所有行)

谢谢

【问题讨论】:

    标签: database python-3.x sqlite


    【解决方案1】:

    如果taskname 是主键,您可以这样做:

    for row in data:
        taskname = row[0]
        # ...
    
        if operator == '<':           
            if coinMarketValue < value and notified == 0: #notified hasnt been set true 
                # ...
                connection.execute("""UPDATE notifyTable 
                                      SET notified = 'True' 
                                      WHERE coinMarketValue < value 
                                      AND notified = 0
                                      AND taskName = ?""",(taskname,))
    

    【讨论】:

    • 哦,天哪,我完全忘记了我什至有那个,甚至没有考虑过那样使用它。谢谢你。这只会改变一行,假设任务名称是唯一的,其他三个条件都为真,对吗?
    • 不客气。没错,假设任务名称是唯一的,它只会更改一行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多