[英]python sqlite3 reopen database
我收到此错误:
sqlite3.ProgrammingError: Cannot operate on a closed database.
关闭数据库后,如何再次打开数据库?
我当时想关闭它,然后重新打开将是一个好主意,因为我有一个循环会运行几个小时:
for x in tweets:
conn = sqlite3.connect("...")
....
conn.close()
time.sleep(1800) #30 minutes
但是,当进入第二个循环时,它给了我关闭的数据库错误。
我会说这里还有其他事情。 我使用Python 2和3运行了以下代码(尽管对于Python 2,我仅使用2秒的time.sleep进行了测试),并且运行良好。
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
分配,则可以得到此代码以产生与您收到的错误相同的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.