简体   繁体   English

python更新中的SQLite3,其中有多个可能的匹配项

[英]SQLite3 in python update where multiple possible matches

Perhaps you can help me.或许你能帮帮我。 I am selecting the oldest # rows in a database, then want to update the date column for each item I selected.我正在选择数据库中最旧的 # 行,然后想要更新我选择的每个项目的日期列。

from datetime import datetime
import sqlite3

conn = sqlite3.connect('testing.db')
cursor = conn.cursor()
# Create the table
cursor.execute('CREATE TABLE IF NOT EXISTS players (player_tag TEXT, update_date TEXT, UNIQUE(player_tag));')
max_player_tags = 2
# Insert some data with old dates
arr = [['tag1','20200123T05:06:07'], ['tag2','20200123T05:06:07'], ['tag3','20200123T05:06:07'], ['tag4', datetime.now().isoformat()]]
cursor.executemany('INSERT OR IGNORE INTO PLAYERS values (?, ?)', arr)
conn.commit()
#Select the oldest 2 items
old_tags = [i[0] for i in cursor.execute('SELECT player_tag FROM players ORDER BY update_date DESC LIMIT 2')]
print(old_tags)
#Now update the dates to now
cursor.execute('UPDATE players SET update_date = datetime("now") WHERE player_tag in %s' % old_tags)
print([i for i in 'SELECT * FROM players'])
cursor.close()
conn.close()

The error I get is我得到的错误是

    cursor.execute('UPDATE players SET update_date = datetime("now") WHERE player_tag in %s' % old_tags)
sqlite3.OperationalError: no such table: 'tag1', 'tag2'
['tag1', 'tag2']

I have also tried:我也试过:

cursor.executemany('INSERT OR IGNORE INTO PLAYERS values (?, ?) ON DUPLICATE KEY UPDATE', upd_arr)

Any ideas?有任何想法吗?

I would just use a single query here:我只想在这里使用一个查询:

sql = """UPDATE players
         SET update_date = datetime("now")
         WHERE player_tag IN (SELECT player_tag FROM players
                              ORDER BY update_date DESC LIMIT 2)"""
cursor.execute(sql)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM