David
David

Reputation: 1569

How can I close a django 1.8 database cursor and connection?

Here is what I have:

from django.db import connection

class Command(BaseCommand):

option_list = BaseCommand.option_list

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;")

Where in this block can I close the db cursor and connection and what do I call to close them?

Upvotes: 1

Views: 5218

Answers (2)

David
David

Reputation: 1569

Found the solution.

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

Thank you

Upvotes: 1

Piyush S. Wanare
Piyush S. Wanare

Reputation: 4933

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

Upvotes: 1

Related Questions