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

标签 python sqlite

也许你可以帮助我。我正在选择数据库中最旧的 # 行,然后想要更新我选择的每个项目的日期列。

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)

有什么想法吗?

最佳答案

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

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)

关于python - python 中的 SQLite3 更新,其中多个可能的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59924087/

相关文章:

python - 列表列表 : find combinations of elements

mysql - 多语言翻译

objective-c - SQLite 数据库图像在 Xcode 中构建时出现格式错误

iOS - 从 UIAlertView 添加数据到 sqlite

python - 获取数据时的 Matplotlib 动画绘图

python - LSTM 的 model.reset_states 会影响模型中的任何其他非 LSTM 层吗?

python - 将 python 时区感知日期时间字符串转换为 utc 时间

java - SQLite 错误插入约束字段 - 为什么?

c - 如何在C中正确进行SQLite SELECT查询?

python - 如何从 Prophet 中提取季节性趋势