From ccf7adb064a70eb1b1ec5857f1dd54988f5c983c Mon Sep 17 00:00:00 2001 From: Chris Jerdonek Date: Wed, 7 Sep 2016 03:14:29 -0700 Subject: [PATCH] Fixed #27172 -- Closed database cursor explicitly in two doc examples --- docs/topics/db/managers.txt | 24 ++++++++++++------------ docs/topics/db/sql.txt | 10 ++++------ 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/docs/topics/db/managers.txt b/docs/topics/db/managers.txt index db147cfb37..7ae6dc7b04 100644 --- a/docs/topics/db/managers.txt +++ b/docs/topics/db/managers.txt @@ -67,18 +67,18 @@ returns a list of all ``OpinionPoll`` objects, each with an extra class PollManager(models.Manager): def with_counts(self): from django.db import connection - cursor = connection.cursor() - cursor.execute(""" - SELECT p.id, p.question, p.poll_date, COUNT(*) - FROM polls_opinionpoll p, polls_response r - WHERE p.id = r.poll_id - GROUP BY p.id, p.question, p.poll_date - ORDER BY p.poll_date DESC""") - result_list = [] - for row in cursor.fetchall(): - p = self.model(id=row[0], question=row[1], poll_date=row[2]) - p.num_responses = row[3] - result_list.append(p) + with connection.cursor() as cursor: + cursor.execute(""" + SELECT p.id, p.question, p.poll_date, COUNT(*) + FROM polls_opinionpoll p, polls_response r + WHERE p.id = r.poll_id + GROUP BY p.id, p.question, p.poll_date + ORDER BY p.poll_date DESC""") + result_list = [] + for row in cursor.fetchall(): + p = self.model(id=row[0], question=row[1], poll_date=row[2]) + p.num_responses = row[3] + result_list.append(p) return result_list class OpinionPoll(models.Model): diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt index a7970928f1..14bf7f9725 100644 --- a/docs/topics/db/sql.txt +++ b/docs/topics/db/sql.txt @@ -250,12 +250,10 @@ For example:: from django.db import connection def my_custom_sql(self): - cursor = connection.cursor() - - cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) - - cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) - row = cursor.fetchone() + with connection.cursor() as cursor: + cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) + cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) + row = cursor.fetchone() return row