2017-02-01 49 views
0

以下是我有:如何關閉django 1.8數據庫遊標和連接?

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

凡在這一塊我可以關閉數據庫光標和連接,我該怎麼調用來關閉它們?

回答

0

找到了解決辦法。

我使用connection.close() 關閉了「with」塊的連接,並解決了這個問題。

謝謝

0

我的建議是嘗試在每個需要查詢的方法中創建和關閉遊標。

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

這僅關閉光標...我希望能夠關閉數據庫連接太...我如何明確地做到這一點? – Becks

+0

當退出'with'模塊時,'cursor'會自動關閉(即使出現異常) –