简体   繁体   中英

python sqlite3 reopen database

Im getting this error:

 sqlite3.ProgrammingError: Cannot operate on a closed database.

How do I open the database again, after I closed it?

I was thinking closing it and then reopening would be a good idea because I have a loop that will be running for several hours:

for x in tweets:
    conn = sqlite3.connect("...")
    ....
    conn.close()
    time.sleep(1800)  #30 minutes

But when it gets to the second loop, it gives me the closed database error.

I'd say there is something else at play here. I ran the following code using Python 2 and 3 (though for Python 2 I only tested with a time.sleep of 2 seconds) and it worked fine.

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

I can get this code to produce the same error you received if I comment out the conn assignment in the for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM