| | 1065 | |
|---|
| | 1066 | Executing custom SQL |
|---|
| | 1067 | -------------------- |
|---|
| | 1068 | |
|---|
| | 1069 | Feel free to write custom SQL statements in custom model methods and |
|---|
| | 1070 | module-level methods. Each custom method automatically has access to the |
|---|
| | 1071 | variable ``db``, which is the current database connection. To use it, call |
|---|
| | 1072 | ``db.cursor()`` to get a cursor object. Then, call ``cursor.execute(sql, [params])`` |
|---|
| | 1073 | to execute the SQL and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return |
|---|
| | 1074 | the resulting rows. Example:: |
|---|
| | 1075 | |
|---|
| | 1076 | def my_custom_sql(self): |
|---|
| | 1077 | cursor = db.cursor() |
|---|
| | 1078 | cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) |
|---|
| | 1079 | row = cursor.fetchone() |
|---|
| | 1080 | return row |
|---|
| | 1081 | |
|---|
| | 1082 | Note that ``db`` and ``cursor`` simply use the standard `Python DB-API`_. |
|---|
| | 1083 | |
|---|
| | 1084 | If you're not familiar with the Python DB-API, note that the SQL statement in |
|---|
| | 1085 | ``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters |
|---|
| | 1086 | directly within the SQL. If you use this technique, the underlying database |
|---|
| | 1087 | library will automatically add quotes and escaping to your parameter(s) as |
|---|
| | 1088 | necessary. |
|---|
| | 1089 | |
|---|
| | 1090 | .. _Python DB-API: http://www.python.org/peps/pep-0249.html |
|---|