python sqlite3重新打开数据库

2024-03-28 21:05:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我收到这个错误:

 sqlite3.ProgrammingError: Cannot operate on a closed database.

关闭数据库后,如何再次打开它?在

我认为关闭它然后重新打开是个好主意,因为我有一个循环,它将运行几个小时:

^{pr2}$

但是当它到达第二个循环时,它会给我一个关闭数据库的错误。在


Tags: 数据库on错误sqlite3database主意closed小时
1条回答
网友
1楼 · 发布于 2024-03-28 21:05:29

我得说这里还有别的事要做。我使用Python2和3运行以下代码(不过对于Python2,我只使用时间。睡觉2秒)而且效果很好。在

import sqlite3, time
conn = sqlite3.connect('example.db')

# Set up table (adding because doing nothing with database didn't cause the error)
c = conn.cursor()
c.execute('CREATE TABLE tweets (tweet text)')
conn.commit()

tweets = ['a','b','c']

for x in tweets:
    print('Tweet: ',x)
    conn = sqlite3.connect("example.db")

    # Extra stuff to try make it error
    c = conn.cursor()
    c.execute('INSERT INTO tweets VALUES (?)', x)
    conn.commit()

    conn.close()
    time.sleep(1800)  #30 minutes


# Cleanup so I can run test a few times
conn = sqlite3.connect("example.db")
c = conn.cursor()
c.execute('DROP TABLE tweets')

如果我在for循环中注释掉conn赋值,我可以让这段代码产生与您收到的相同的错误。在

相关问题 更多 >