代码之家  ›  专栏  ›  技术社区  ›  David

如何关闭django 1.8数据库游标和连接?

  •  0
  • David  · 技术社区  · 9 年前

    以下是我所拥有的:

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

    在这个块中,我在哪里可以关闭db游标和连接?我应该调用什么来关闭它们?

    2 回复  |  直到 9 年前
        1
  •  1
  •   David    9 年前

    找到了解决方案。

    我用connection.close()关闭“with”块中的连接 这就解决了这个问题。

    非常感谢。

        2
  •  0
  •   Piyush S. Wanare    9 年前

    我的建议是尝试在需要查询的每个方法中创建和关闭光标。

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

    因此,您的函数应该如下所示:

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