Py学习  »  Python

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

user2460638 • 5 年前 • 1419 次点击  

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()

我得到的错误是

    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']

我也试过:

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56195
 
1419 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Tim Biegeleisen
Reply   •   1 楼
Tim Biegeleisen    5 年前

我只需要在这里使用一个查询:

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)