英文:
Can I change the DB while the cycle is checking it? sqlite3
问题
我想知道在从数据库每10秒获取数据的循环运行时是否可以更改数据库。库是aiosqlite。
循环的代码:
db = await aiosqlite.connect("/main.db")
while True:
await asyncio.sleep(10.5)
ti = await db.execute_fetchall("SELECT delete_time FROM auction WHERE id = ?", (id,))
print("来自数据库的检查", ti[0][0])
if float(ti[0][0]) > dt.now().timestamp():
continue
else:
return True
更改的代码:
db = await aiosqlite.connect("/main.db")
timing = await db.execute_fetchall("SELECT delete_time FROM auction WHERE id = ?", (id,))
print("来自数据库", timing[0][0])
timing = float(timing[0][0]) + 60
print("已编辑", timing)
await db.execute("UPDATE auction SET delete_time = ? WHERE id = ?", (timing, id,))
await db.close()
看起来没有错误,但在数据库中什么都没有改变(当我写入命令时,数据库才会发生变化)。
英文:
I'm interested to know if I can change the DB while the loop is running that takes data from the database every 10 seconds? The library is aiosqlite.
The code of the loop:
db = await aiosqlite.connect("/main.db")
while True:
await asyncio.sleep(10.5)
ti = await db.execute_fetchall("SELECT delete_time FROM auction WHERE id = ?", (id,))
print("from db check", ti[0][0])
if float(ti[0][0]) > dt.now().timestamp():
continue
else:
return True
Change code:
db = await aiosqlite.connect("/main.db")
timing = await db.execute_fetchall("SELECT delete_time FROM auction WHERE id = ?", (id,))
print("from db", timing[0][0])
timing = float(timing[0][0]) + 60
print("edited", timing)
await db.execute("UPDATE auction SET delete_time = ? WHERE id = ?", (timing, id,))
await db.close()
There seem to be no errors, but nothing changes in the DB (the DB changes when I write a command).
答案1
得分: 0
你需要添加 await db.commit()
以便将更改持久化。
db = await aiosqlite.connect("/main.db")
timing = await db.execute_fetchall("SELECT delete_time FROM auction WHERE id = ?", (id,))
print("from db", timing[0][0])
timing = float(timing[0][0]) + 60
print("edited", timing)
await db.execute("UPDATE auction SET delete_time = ? WHERE id = ?", (timing, id,))
await db.commit() # 持久化更改
await db.close()
英文:
You're missing a await db.commit()
if you want to persist the changes.
db = await aiosqlite.connect("/main.db")
timing = await db.execute_fetchall("SELECT delete_time FROM auction WHERE id = ?", (id,))
print("from db", timing[0][0])
timing = float(timing[0][0]) + 60
print("edited", timing)
await db.execute("UPDATE auction SET delete_time = ? WHERE id = ?", (timing, id,))
await db.commit() # persist changes
await db.close()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论