[Answered ]-How can I close a django 1.8 database cursor and connection?

1👍

Found the solution.

I close the connection out of the “with” block with connection.close()
and that solves it.

Thank you

👤David

1👍

My suggestion is try to create and close the cursor within each method where query is needed.

cursor = connection.cursor()
cursor.execute(query)
cursor.close()

So your function should look like this:

def handle(self, *labels, **options):
    with connection.cursor() as cursor:
        # Drop database 
        cursor.execute("drop database if exists test_db;")
        # Create database again
        cursor.execute("create database test_db;")
        #Close the cursor
        cursor.close()

Leave a comment