【问题标题】:How can I close a django 1.8 database cursor and connection?如何关闭 django 1.8 数据库游标和连接?
【发布时间】:2017-06-17 17:53:05
【问题描述】:

这是我所拥有的:

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

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

【问题讨论】:

    标签: python django postgresql connection django-1.8


    【解决方案1】:

    找到了解决办法。

    我用connection.close()从“with”块中关闭连接 这解决了它。

    谢谢

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这只是关闭光标......我也希望能够关闭 DATABASE CONNECTION......我该如何明确地做到这一点?
      • cursor 在退出with 块时会自动关闭(即使出现异常)
      猜你喜欢
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 2012-11-16
      相关资源
      最近更新 更多