循环遍历各行并更新SQLite3 Python的那些行

时间:2017-08-23 22:38:13

标签: database python-3.x sqlite

我有下表: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()

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

coinMarketValue < value AND notified == 0

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

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

由于

1 个答案:

答案 0 :(得分: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,))