diff options
| author | Jacob Kaplan-Moss <jacob@jacobian.org> | 2008-08-23 22:25:40 +0000 |
|---|---|---|
| committer | Jacob Kaplan-Moss <jacob@jacobian.org> | 2008-08-23 22:25:40 +0000 |
| commit | 97cb07c3a10ff0e584a260a7ee1001614691eb1d (patch) | |
| tree | 204f4382c51e1c288dbf547875161731661733f5 /docs/topics/db/sql.txt | |
| parent | b3688e81943d6d059d3f3c95095498a5aab84852 (diff) | |
Massive reorganization of the docs. See the new docs online at http://docs.djangoproject.com/.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8506 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'docs/topics/db/sql.txt')
| -rw-r--r-- | docs/topics/db/sql.txt | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt new file mode 100644 index 0000000000..21cceba58b --- /dev/null +++ b/docs/topics/db/sql.txt @@ -0,0 +1,35 @@ +.. _topics-db-sql: + +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:: + + def my_custom_sql(self): + from django.db import connection + cursor = connection.cursor() + 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`_ +(except when it comes to :ref:`transaction handling <topics-db-transactions>`). +If you're not familiar with the Python DB-API, note that the SQL statement in +``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters +directly within the SQL. If you use this technique, the underlying database +library will automatically add quotes and escaping to your parameter(s) as +necessary. (Also note that Django expects the ``"%s"`` placeholder, *not* the +``"?"`` placeholder, which is used by the SQLite Python bindings. This is for +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. + +.. _Python DB-API: http://www.python.org/peps/pep-0249.html + |
