summaryrefslogtreecommitdiff
path: root/docs/topics/db/sql.txt
diff options
context:
space:
mode:
authorRussell Keith-Magee <russell@keith-magee.com>2009-05-02 07:40:25 +0000
committerRussell Keith-Magee <russell@keith-magee.com>2009-05-02 07:40:25 +0000
commit87d3ff731bfbedaefa8cb762c92df18e5d234978 (patch)
tree373564c7a4536d82c736dc874615e4b36671966e /docs/topics/db/sql.txt
parente85bc81651abfc417e57aadf3dd7bed137c80430 (diff)
Fixed #9206 -- Clarified documentation of transaction handling in raw SQL, and error recovery for Postgres. Thanks to Richard Davies for the suggestion and draft text.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10655 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'docs/topics/db/sql.txt')
-rw-r--r--docs/topics/db/sql.txt24
1 files changed, 18 insertions, 6 deletions
diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt
index 21cceba58b..4352908909 100644
--- a/docs/topics/db/sql.txt
+++ b/docs/topics/db/sql.txt
@@ -5,16 +5,28 @@ Performing raw SQL queries
Feel free to write custom SQL statements in custom model methods and
module-level methods. The object ``django.db.connection`` represents the
-current database connection. To use it, call ``connection.cursor()`` to get a
-cursor object. Then, call ``cursor.execute(sql, [params])`` to execute the SQL
-and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return the resulting
-rows. Example::
+current database connection, and ``django.db.transaction`` represents the
+current database transaction. To use the database connection, call
+``connection.cursor()`` to get a cursor object. Then, call
+``cursor.execute(sql, [params])`` to execute the SQL and ``cursor.fetchone()``
+or ``cursor.fetchall()`` to return the resulting rows. After performing a data
+changing operation, you should then call
+``transaction.commit_unless_managed()`` to ensure your changes are committed
+to the database. If your query is purely a data retrieval operation, no commit
+is required. For example::
def my_custom_sql(self):
- from django.db import connection
+ from django.db import connection, transaction
cursor = connection.cursor()
+
+ # Data modifying operation - commit required
+ cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
+ transaction.commit_unless_managed()
+
+ # Data retrieval operation - no commit required
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
+
return row
``connection`` and ``cursor`` mostly implement the standard `Python DB-API`_
@@ -29,7 +41,7 @@ the sake of consistency and sanity.)
A final note: If all you want to do is a custom ``WHERE`` clause, you can just
use the ``where``, ``tables`` and ``params`` arguments to the standard lookup
-API.
+API.
.. _Python DB-API: http://www.python.org/peps/pep-0249.html