Sqlite python sqlite3.OperationalError: database is locked

前端 未结 4 1067
野的像风
野的像风 2020-12-17 17:45

I have written the following code, which is showing the sqlite3.OperationalError: database is locked error. Any help to debug would be much appreciated.

相关标签:
4条回答
  • 2020-12-17 18:18
    cursor2 = conn.cursor()
    cursor3 = conn.cursor()
    cursor4 = conn.cursor()
    

    I think you have to close the connection which you have opened,may be the error is because of that cause you have opened multiple connections.

    cursor2 = conn.cursor()
    """EDIT YOUR DATABASE USING CODE AND CLOSE THE CONNECTION"""
    connection.close()
    
    cursor3 = conn.cursor()
    """EDIT YOUR DATABASE USING CODE AND CLOSE THE CONNECTION"""
    connection.close()
    
    cursor4 = conn.cursor()
    """EDIT YOUR DATABASE USING CODE AND CLOSE THE CONNECTION"""
    connection.close()
    
    0 讨论(0)
  • 2020-12-17 18:29

    "Database is locked" means that some other connection has an active connection.

    Use PRAGMA busy_timeout to wait some time for the other transaction to finish:

    conn.execute("PRAGMA busy_timeout = 30000")   # 30 s
    

    However, if that other application deliberately keeps an open transaction to keep the database locked, there is nothing you can do.

    0 讨论(0)
  • 2020-12-17 18:32

    I'm not sure if this will help anyone, but I figured out a solution to my own Locked Database problem.

    I use PyCharm and found that several instances of the script I was working on were all running. This was usually due to errors in the code I was testing, but it stayed active (and therefore the connection to the db was still active). Close out of those (stop all the processes) and try again - it has worked every time for me!

    If anyone knows a way to make it timeout after a little while, please comment this solution. I tried cur.execute("PRAGMA busy_timeout = 30000") (found from another thread on a similar question) but it didn't seem to do anything.

    0 讨论(0)
  • 2020-12-17 18:35

    I had the same issue but it was resolved when I used the following to close the concurrent connections.

    conn.close()
    

    So, if your program begins like this:

    import sqlite3
    
    conn = sqlite3.connect('pg_example.db', timeout=10)
    c = conn.cursor()
    

    Make sure that you're including the conn.close() after each SQL statement

    t = ('RHAT',)
    c.execute('SELECT * FROM stocks WHERE symbol=?', t)
    conn.commit()
    conn.close() #This is the one you need
    
    0 讨论(0)
提交回复
热议问题