优雅的方式来更新Sqlite3 Python的多个值

时间:2015-01-05 02:15:38

标签: python python-2.7 sqlite

我有一个名为 MYTABLE Sqlite3数据库,如下所示:

enter image description here

我的目标是通过简单地将现有值与新值相加来更新 COUNT 列的值。

我将收到两个输入:

  1. 首先,我需要为 COUNT 列更新ID。 例如:['1','3','2','5']
  2. 其次,要添加到每个ID的计数数量 上面的清单。
  3. 到目前为止,我能想到的最好的是:

    #my input1, the list of IDs that need updating
    id_list = ['1','2','5','3']
    
    #my input2, the value to be added to the existing count value
    new_count = 3
    
    #empty list to store the original count values before updating
    original_counts = []
    
    #iterate through the input1 and retrieve the original count values
    for item in id_list :
        cursor = conn.execute("SELECT COUNT from MYTABLE where ID=?",[item])
        for row in cursor:
            original_counts.append(row[0])
    
    #iterate through the input1 and update the count values
    for i in range(len(id_list )):
        conn.execute("UPDATE MYTABLE set COUNT = ? where ID=?",[original_counts[i]+new_count ,mylist[i])
    

    是否有更好/更优雅,更有效的方式来实现我想要的目标?

    更新1:

    我根据N Reed的回答(不完全相同)尝试了这个,并且它有效!

    for item in mylist:
        conn.execute("UPDATE MYTABLE set VAL=VAL+? where ID=?",[new_count,item])
    

    离开我我们可以根据它的当前值(我不知道)更新sqlite3中的值

1 个答案:

答案 0 :(得分:0)

您想要创建如下所示的查询:

UPDATE MYTABLE set COUNT = COUNT + 5 where ID in (1, 2, 3, 4)

我不太了解python,但你可能想要python中的代码:

conn.execute("UPDATE MYTABLE set COUNT = COUNT + ? where ID in (?)", new_count , ",".join(mylist))

请注意,使用sqllite在Id列表中可以拥有的项目数量有限制(我认为它类似于1000)

当您以这种方式创建查询时,还要非常小心sql注入。您可能希望确保mylist中的所有项目都已在其他位置转义。

我还建议不要使用名为' count'因为它是sql中的关键字。