pythonsqlite

Using functions to open/close sqlite db connections?


Being new to both Python and sqlite, I've been playing around with them both recently trying to figure things out. In particular with sqlite I've learned how to open/close/commit data to a db. But now I'm trying to clean things up a bit so that I can open/close the db via function calls. For instance, I'd like to do something like:

def open_db():
    conn = sqlite3.connect("path")
    c = conn.cursor()

def close_db():    
    c.close()
    conn.close()

def create_db():
    open_db()
    c.execute("CREATE STUFF")
    close_db()

Then when I run the program, before I query or write to the table, I could do something like:

open_db()
c.execute('SELECT * DO STUFF')
OR
c.execute('DELETE * DO OTHER STUFF')
conn.commit
close_db()

I've read about context managers but I'm not sure I understand entirely whats going on with them. What would be the easiest solution to cleaning up the way I open/close my DB connections so I'm not always having to type in the cursor command.


Solution

  • This is because the connection you define is local to the open db function. Change it as follows

    def open_db():
        conn = sqlite3.connect("path")
        return conn.cursor()
    

    and then

    c = open_db()
    c.execute('SELECT * DO STUFF')
    

    It should be noted that writing function like this purely as a learning exercise might be ok, but generally it's not very useful to write a thin wrapper around a database connectivity api.