pythonsqlobject

Closing an SQLObject Connection


Is it possible to manually close an SQLObject Connection once it has been opened? I am trying to delete a database file once it has been used, but it seems that the open connection to the database file is stopping me from doing so.

For example:

from sqlobject import *
import os

# Create and open connection to a database file.
sqlhub.processConnection = connectionForURI('sqlite:path_to_db')
SomeObject.createTable()

# ...

# Delete database when finished.
os.remove('path_to_db')

Gives the following error:

WindowsError: [Error 32] The process cannot access the file because 
              it is being used by another process: 'path_to_db'

Solution

  • It seems like just calling .close() on the database connection seems to do the trick:

    from sqlobject import *
    import os
    
    # Create and open connection to a database file.
    sqlhub.processConnection = connectionForURI('sqlite:path_to_db')
    
    #do something with connection
    pass
    
    #close connection
    sqlhub.processConnection.close()
    
    #delete database
    os.remove(path_to_db)
    

    I could only find a little bit on the close method here, but it's fair to say you can treat it like any other file object. I don't have much experience with sqlobject though, and in the interpreter, you can still remove the db right after the processConnection assignment, without closing it, so who knows.