blob: 28edfcff215a8c7b7aab3beef4a66254f0443e5e [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`sqlite3` --- DB-API 2.0 interface for SQLite databases
2============================================================
3
4.. module:: sqlite3
5 :synopsis: A DB-API 2.0 implementation using SQLite 3.x.
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +02006.. sectionauthor:: Gerhard Häring <gh@ghaering.de>
Georg Brandl116aa622007-08-15 14:28:22 +00007
8
Georg Brandl116aa622007-08-15 14:28:22 +00009SQLite is a C library that provides a lightweight disk-based database that
10doesn't require a separate server process and allows accessing the database
11using a nonstandard variant of the SQL query language. Some applications can use
12SQLite for internal data storage. It's also possible to prototype an
13application using SQLite and then port the code to a larger database such as
14PostgreSQL or Oracle.
15
Georg Brandl8a1e4c42009-05-25 21:13:36 +000016sqlite3 was written by Gerhard Häring and provides a SQL interface compliant
Georg Brandl116aa622007-08-15 14:28:22 +000017with the DB-API 2.0 specification described by :pep:`249`.
18
19To use the module, you must first create a :class:`Connection` object that
20represents the database. Here the data will be stored in the
21:file:`/tmp/example` file::
22
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020023 import sqlite3
Georg Brandl116aa622007-08-15 14:28:22 +000024 conn = sqlite3.connect('/tmp/example')
25
26You can also supply the special name ``:memory:`` to create a database in RAM.
27
28Once you have a :class:`Connection`, you can create a :class:`Cursor` object
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000029and call its :meth:`~Cursor.execute` method to perform SQL commands::
Georg Brandl116aa622007-08-15 14:28:22 +000030
31 c = conn.cursor()
32
33 # Create table
34 c.execute('''create table stocks
35 (date text, trans text, symbol text,
36 qty real, price real)''')
37
38 # Insert a row of data
39 c.execute("""insert into stocks
40 values ('2006-01-05','BUY','RHAT',100,35.14)""")
41
42 # Save (commit) the changes
43 conn.commit()
44
45 # We can also close the cursor if we are done with it
46 c.close()
47
48Usually your SQL operations will need to use values from Python variables. You
49shouldn't assemble your query using Python's string operations because doing so
50is insecure; it makes your program vulnerable to an SQL injection attack.
51
52Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
53wherever you want to use a value, and then provide a tuple of values as the
Georg Brandl8a1e4c42009-05-25 21:13:36 +000054second argument to the cursor's :meth:`~Cursor.execute` method. (Other database
55modules may use a different placeholder, such as ``%s`` or ``:1``.) For
56example::
Georg Brandl116aa622007-08-15 14:28:22 +000057
58 # Never do this -- insecure!
59 symbol = 'IBM'
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020060 c.execute("select * from stocks where symbol = '%s'" % symbol)
Georg Brandl116aa622007-08-15 14:28:22 +000061
62 # Do this instead
R David Murrayf6bd1b02012-08-20 14:14:18 -040063 t = ('IBM',)
Georg Brandl116aa622007-08-15 14:28:22 +000064 c.execute('select * from stocks where symbol=?', t)
65
66 # Larger example
Georg Brandla971c652008-11-07 09:39:56 +000067 for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020068 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
Georg Brandl116aa622007-08-15 14:28:22 +000069 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
Georg Brandla971c652008-11-07 09:39:56 +000070 ]:
Georg Brandl116aa622007-08-15 14:28:22 +000071 c.execute('insert into stocks values (?,?,?,?,?)', t)
72
Georg Brandl9afde1c2007-11-01 20:32:30 +000073To retrieve data after executing a SELECT statement, you can either treat the
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000074cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
75retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandl9afde1c2007-11-01 20:32:30 +000076matching rows.
Georg Brandl116aa622007-08-15 14:28:22 +000077
78This example uses the iterator form::
79
80 >>> c = conn.cursor()
81 >>> c.execute('select * from stocks order by price')
82 >>> for row in c:
Ezio Melottib5845052009-09-13 05:49:25 +000083 ... print(row)
Georg Brandl116aa622007-08-15 14:28:22 +000084 ...
Ezio Melottib5845052009-09-13 05:49:25 +000085 ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
86 ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
87 ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
88 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.0)
Georg Brandl116aa622007-08-15 14:28:22 +000089 >>>
90
91
92.. seealso::
93
Benjamin Peterson2614cda2010-03-21 22:36:19 +000094 http://code.google.com/p/pysqlite/
Georg Brandl8a1e4c42009-05-25 21:13:36 +000095 The pysqlite web page -- sqlite3 is developed externally under the name
96 "pysqlite".
Georg Brandl116aa622007-08-15 14:28:22 +000097
98 http://www.sqlite.org
Georg Brandl8a1e4c42009-05-25 21:13:36 +000099 The SQLite web page; the documentation describes the syntax and the
100 available data types for the supported SQL dialect.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102 :pep:`249` - Database API Specification 2.0
103 PEP written by Marc-André Lemburg.
104
105
106.. _sqlite3-module-contents:
107
108Module functions and constants
109------------------------------
110
111
R David Murray3f7beb92013-01-10 20:18:21 -0500112.. data:: version
113
114 The version number of this module, as a string. This is not the version of
115 the SQLite library.
116
117
118.. data:: version_info
119
120 The version number of this module, as a tuple of integers. This is not the
121 version of the SQLite library.
122
123
124.. data:: sqlite_version
125
126 The version number of the run-time SQLite library, as a string.
127
128
129.. data:: sqlite_version_info
130
131 The version number of the run-time SQLite library, as a tuple of integers.
132
133
Georg Brandl116aa622007-08-15 14:28:22 +0000134.. data:: PARSE_DECLTYPES
135
136 This constant is meant to be used with the *detect_types* parameter of the
137 :func:`connect` function.
138
139 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000140 column it returns. It will parse out the first word of the declared type,
141 i. e. for "integer primary key", it will parse out "integer", or for
142 "number(10)" it will parse out "number". Then for that column, it will look
143 into the converters dictionary and use the converter function registered for
144 that type there.
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146
147.. data:: PARSE_COLNAMES
148
149 This constant is meant to be used with the *detect_types* parameter of the
150 :func:`connect` function.
151
152 Setting this makes the SQLite interface parse the column name for each column it
153 returns. It will look for a string formed [mytype] in there, and then decide
154 that 'mytype' is the type of the column. It will try to find an entry of
155 'mytype' in the converters dictionary and then use the converter function found
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000156 there to return the value. The column name found in :attr:`Cursor.description`
Georg Brandl116aa622007-08-15 14:28:22 +0000157 is only the first word of the column name, i. e. if you use something like
158 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
159 first blank for the column name: the column name would simply be "x".
160
161
Georg Brandl1c616a52010-07-10 12:01:34 +0000162.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164 Opens a connection to the SQLite database file *database*. You can use
165 ``":memory:"`` to open a database connection to a database that resides in RAM
166 instead of on disk.
167
168 When a database is accessed by multiple connections, and one of the processes
169 modifies the database, the SQLite database is locked until that transaction is
170 committed. The *timeout* parameter specifies how long the connection should wait
171 for the lock to go away until raising an exception. The default for the timeout
172 parameter is 5.0 (five seconds).
173
174 For the *isolation_level* parameter, please see the
175 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
176
177 SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
178 you want to use other types you must add support for them yourself. The
179 *detect_types* parameter and the using custom **converters** registered with the
180 module-level :func:`register_converter` function allow you to easily do that.
181
182 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
183 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
184 type detection on.
185
186 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
187 connect call. You can, however, subclass the :class:`Connection` class and make
188 :func:`connect` use your class instead by providing your class for the *factory*
189 parameter.
190
191 Consult the section :ref:`sqlite3-types` of this manual for details.
192
193 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
194 overhead. If you want to explicitly set the number of statements that are cached
195 for the connection, you can set the *cached_statements* parameter. The currently
196 implemented default is to cache 100 statements.
197
198
199.. function:: register_converter(typename, callable)
200
201 Registers a callable to convert a bytestring from the database into a custom
202 Python type. The callable will be invoked for all database values that are of
203 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
204 function for how the type detection works. Note that the case of *typename* and
205 the name of the type in your query must match!
206
207
208.. function:: register_adapter(type, callable)
209
210 Registers a callable to convert the custom Python type *type* into one of
211 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000212 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000213 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215
216.. function:: complete_statement(sql)
217
218 Returns :const:`True` if the string *sql* contains one or more complete SQL
219 statements terminated by semicolons. It does not verify that the SQL is
220 syntactically correct, only that there are no unclosed string literals and the
221 statement is terminated by a semicolon.
222
223 This can be used to build a shell for SQLite, as in the following example:
224
225
226 .. literalinclude:: ../includes/sqlite3/complete_statement.py
227
228
229.. function:: enable_callback_tracebacks(flag)
230
231 By default you will not get any tracebacks in user-defined functions,
232 aggregates, converters, authorizer callbacks etc. If you want to debug them, you
233 can call this function with *flag* as True. Afterwards, you will get tracebacks
234 from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
235 again.
236
237
238.. _sqlite3-connection-objects:
239
240Connection Objects
241------------------
242
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000243.. class:: Connection
244
245 A SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000246
R David Murray6db23352012-09-30 20:44:43 -0400247 .. attribute:: isolation_level
Georg Brandl116aa622007-08-15 14:28:22 +0000248
R David Murray6db23352012-09-30 20:44:43 -0400249 Get or set the current isolation level. :const:`None` for autocommit mode or
250 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
251 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000252
R David Murray6db23352012-09-30 20:44:43 -0400253 .. attribute:: in_transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000254
R David Murray6db23352012-09-30 20:44:43 -0400255 :const:`True` if a transaction is active (there are uncommitted changes),
256 :const:`False` otherwise. Read-only attribute.
R. David Murrayd35251d2010-06-01 01:32:12 +0000257
R David Murray6db23352012-09-30 20:44:43 -0400258 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000259
R David Murray6db23352012-09-30 20:44:43 -0400260 .. method:: cursor([cursorClass])
Georg Brandl116aa622007-08-15 14:28:22 +0000261
R David Murray6db23352012-09-30 20:44:43 -0400262 The cursor method accepts a single optional parameter *cursorClass*. If
263 supplied, this must be a custom cursor class that extends
264 :class:`sqlite3.Cursor`.
Georg Brandl116aa622007-08-15 14:28:22 +0000265
R David Murray6db23352012-09-30 20:44:43 -0400266 .. method:: commit()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000267
R David Murray6db23352012-09-30 20:44:43 -0400268 This method commits the current transaction. If you don't call this method,
269 anything you did since the last call to ``commit()`` is not visible from
270 other database connections. If you wonder why you don't see the data you've
271 written to the database, please check you didn't forget to call this method.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000272
R David Murray6db23352012-09-30 20:44:43 -0400273 .. method:: rollback()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000274
R David Murray6db23352012-09-30 20:44:43 -0400275 This method rolls back any changes to the database since the last call to
276 :meth:`commit`.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000277
R David Murray6db23352012-09-30 20:44:43 -0400278 .. method:: close()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000279
R David Murray6db23352012-09-30 20:44:43 -0400280 This closes the database connection. Note that this does not automatically
281 call :meth:`commit`. If you just close your database connection without
282 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000283
R David Murray6db23352012-09-30 20:44:43 -0400284 .. method:: execute(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000285
R David Murray6db23352012-09-30 20:44:43 -0400286 This is a nonstandard shortcut that creates an intermediate cursor object by
287 calling the cursor method, then calls the cursor's :meth:`execute
288 <Cursor.execute>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290
R David Murray6db23352012-09-30 20:44:43 -0400291 .. method:: executemany(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000292
R David Murray6db23352012-09-30 20:44:43 -0400293 This is a nonstandard shortcut that creates an intermediate cursor object by
294 calling the cursor method, then calls the cursor's :meth:`executemany
295 <Cursor.executemany>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000296
R David Murray6db23352012-09-30 20:44:43 -0400297 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000298
R David Murray6db23352012-09-30 20:44:43 -0400299 This is a nonstandard shortcut that creates an intermediate cursor object by
300 calling the cursor method, then calls the cursor's :meth:`executescript
301 <Cursor.executescript>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000302
303
R David Murray6db23352012-09-30 20:44:43 -0400304 .. method:: create_function(name, num_params, func)
Georg Brandl116aa622007-08-15 14:28:22 +0000305
R David Murray6db23352012-09-30 20:44:43 -0400306 Creates a user-defined function that you can later use from within SQL
307 statements under the function name *name*. *num_params* is the number of
308 parameters the function accepts, and *func* is a Python callable that is called
309 as the SQL function.
Georg Brandl116aa622007-08-15 14:28:22 +0000310
R David Murray6db23352012-09-30 20:44:43 -0400311 The function can return any of the types supported by SQLite: bytes, str, int,
312 float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
R David Murray6db23352012-09-30 20:44:43 -0400314 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000315
R David Murray6db23352012-09-30 20:44:43 -0400316 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl116aa622007-08-15 14:28:22 +0000317
318
R David Murray6db23352012-09-30 20:44:43 -0400319 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl116aa622007-08-15 14:28:22 +0000320
R David Murray6db23352012-09-30 20:44:43 -0400321 Creates a user-defined aggregate function.
Georg Brandl116aa622007-08-15 14:28:22 +0000322
R David Murray6db23352012-09-30 20:44:43 -0400323 The aggregate class must implement a ``step`` method, which accepts the number
324 of parameters *num_params*, and a ``finalize`` method which will return the
325 final result of the aggregate.
Georg Brandl116aa622007-08-15 14:28:22 +0000326
R David Murray6db23352012-09-30 20:44:43 -0400327 The ``finalize`` method can return any of the types supported by SQLite:
328 bytes, str, int, float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000329
R David Murray6db23352012-09-30 20:44:43 -0400330 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000331
R David Murray6db23352012-09-30 20:44:43 -0400332 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334
R David Murray6db23352012-09-30 20:44:43 -0400335 .. method:: create_collation(name, callable)
Georg Brandl116aa622007-08-15 14:28:22 +0000336
R David Murray6db23352012-09-30 20:44:43 -0400337 Creates a collation with the specified *name* and *callable*. The callable will
338 be passed two string arguments. It should return -1 if the first is ordered
339 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
340 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
341 your comparisons don't affect other SQL operations.
Georg Brandl116aa622007-08-15 14:28:22 +0000342
R David Murray6db23352012-09-30 20:44:43 -0400343 Note that the callable will get its parameters as Python bytestrings, which will
344 normally be encoded in UTF-8.
Georg Brandl116aa622007-08-15 14:28:22 +0000345
R David Murray6db23352012-09-30 20:44:43 -0400346 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl116aa622007-08-15 14:28:22 +0000347
R David Murray6db23352012-09-30 20:44:43 -0400348 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl116aa622007-08-15 14:28:22 +0000349
R David Murray6db23352012-09-30 20:44:43 -0400350 To remove a collation, call ``create_collation`` with None as callable::
Georg Brandl116aa622007-08-15 14:28:22 +0000351
R David Murray6db23352012-09-30 20:44:43 -0400352 con.create_collation("reverse", None)
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354
R David Murray6db23352012-09-30 20:44:43 -0400355 .. method:: interrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000356
R David Murray6db23352012-09-30 20:44:43 -0400357 You can call this method from a different thread to abort any queries that might
358 be executing on the connection. The query will then abort and the caller will
359 get an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361
R David Murray6db23352012-09-30 20:44:43 -0400362 .. method:: set_authorizer(authorizer_callback)
Georg Brandl116aa622007-08-15 14:28:22 +0000363
R David Murray6db23352012-09-30 20:44:43 -0400364 This routine registers a callback. The callback is invoked for each attempt to
365 access a column of a table in the database. The callback should return
366 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
367 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
368 column should be treated as a NULL value. These constants are available in the
369 :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
R David Murray6db23352012-09-30 20:44:43 -0400371 The first argument to the callback signifies what kind of operation is to be
372 authorized. The second and third argument will be arguments or :const:`None`
373 depending on the first argument. The 4th argument is the name of the database
374 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
375 inner-most trigger or view that is responsible for the access attempt or
376 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl116aa622007-08-15 14:28:22 +0000377
R David Murray6db23352012-09-30 20:44:43 -0400378 Please consult the SQLite documentation about the possible values for the first
379 argument and the meaning of the second and third argument depending on the first
380 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382
R David Murray6db23352012-09-30 20:44:43 -0400383 .. method:: set_progress_handler(handler, n)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000384
R David Murray6db23352012-09-30 20:44:43 -0400385 This routine registers a callback. The callback is invoked for every *n*
386 instructions of the SQLite virtual machine. This is useful if you want to
387 get called from SQLite during long-running operations, for example to update
388 a GUI.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000389
R David Murray6db23352012-09-30 20:44:43 -0400390 If you want to clear any previously installed progress handler, call the
391 method with :const:`None` for *handler*.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000392
393
R David Murray6db23352012-09-30 20:44:43 -0400394 .. method:: enable_load_extension(enabled)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000395
R David Murray6db23352012-09-30 20:44:43 -0400396 This routine allows/disallows the SQLite engine to load SQLite extensions
397 from shared libraries. SQLite extensions can define new functions,
398 aggregates or whole new virtual table implementations. One well-known
399 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000400
R David Murray6db23352012-09-30 20:44:43 -0400401 Loadable extensions are disabled by default. See [#f1]_.
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200402
R David Murray6db23352012-09-30 20:44:43 -0400403 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000404
R David Murray6db23352012-09-30 20:44:43 -0400405 .. literalinclude:: ../includes/sqlite3/load_extension.py
Gerhard Häringf9cee222010-03-05 15:20:03 +0000406
R David Murray6db23352012-09-30 20:44:43 -0400407 .. method:: load_extension(path)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000408
R David Murray6db23352012-09-30 20:44:43 -0400409 This routine loads a SQLite extension from a shared library. You have to
410 enable extension loading with :meth:`enable_load_extension` before you can
411 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000412
R David Murray6db23352012-09-30 20:44:43 -0400413 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringe0941c52010-10-03 21:47:06 +0000414
R David Murray6db23352012-09-30 20:44:43 -0400415 .. versionadded:: 3.2
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200416
R David Murray6db23352012-09-30 20:44:43 -0400417 .. attribute:: row_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000418
R David Murray6db23352012-09-30 20:44:43 -0400419 You can change this attribute to a callable that accepts the cursor and the
420 original row as a tuple and will return the real result row. This way, you can
421 implement more advanced ways of returning results, such as returning an object
422 that can also access columns by name.
Georg Brandl116aa622007-08-15 14:28:22 +0000423
R David Murray6db23352012-09-30 20:44:43 -0400424 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000425
R David Murray6db23352012-09-30 20:44:43 -0400426 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000427
R David Murray6db23352012-09-30 20:44:43 -0400428 If returning a tuple doesn't suffice and you want name-based access to
429 columns, you should consider setting :attr:`row_factory` to the
430 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
431 index-based and case-insensitive name-based access to columns with almost no
432 memory overhead. It will probably be better than your own custom
433 dictionary-based approach or even a db_row based solution.
Georg Brandl116aa622007-08-15 14:28:22 +0000434
R David Murray6db23352012-09-30 20:44:43 -0400435 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000436
437
R David Murray6db23352012-09-30 20:44:43 -0400438 .. attribute:: text_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000439
R David Murray6db23352012-09-30 20:44:43 -0400440 Using this attribute you can control what objects are returned for the ``TEXT``
441 data type. By default, this attribute is set to :class:`str` and the
442 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
443 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000444
R David Murray6db23352012-09-30 20:44:43 -0400445 For efficiency reasons, there's also a way to return :class:`str` objects
446 only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
447 this attribute to :const:`sqlite3.OptimizedUnicode`.
Georg Brandl116aa622007-08-15 14:28:22 +0000448
R David Murray6db23352012-09-30 20:44:43 -0400449 You can also set it to any other callable that accepts a single bytestring
450 parameter and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000451
R David Murray6db23352012-09-30 20:44:43 -0400452 See the following example code for illustration:
Georg Brandl116aa622007-08-15 14:28:22 +0000453
R David Murray6db23352012-09-30 20:44:43 -0400454 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456
R David Murray6db23352012-09-30 20:44:43 -0400457 .. attribute:: total_changes
Georg Brandl116aa622007-08-15 14:28:22 +0000458
R David Murray6db23352012-09-30 20:44:43 -0400459 Returns the total number of database rows that have been modified, inserted, or
460 deleted since the database connection was opened.
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462
R David Murray6db23352012-09-30 20:44:43 -0400463 .. attribute:: iterdump
Christian Heimesbbe741d2008-03-28 10:53:29 +0000464
R David Murray6db23352012-09-30 20:44:43 -0400465 Returns an iterator to dump the database in an SQL text format. Useful when
466 saving an in-memory database for later restoration. This function provides
467 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
468 shell.
Christian Heimesbbe741d2008-03-28 10:53:29 +0000469
R David Murray6db23352012-09-30 20:44:43 -0400470 Example::
Christian Heimesbbe741d2008-03-28 10:53:29 +0000471
R David Murray6db23352012-09-30 20:44:43 -0400472 # Convert file existing_db.db to SQL dump file dump.sql
473 import sqlite3, os
Christian Heimesbbe741d2008-03-28 10:53:29 +0000474
R David Murray6db23352012-09-30 20:44:43 -0400475 con = sqlite3.connect('existing_db.db')
476 with open('dump.sql', 'w') as f:
477 for line in con.iterdump():
478 f.write('%s\n' % line)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000479
480
Georg Brandl116aa622007-08-15 14:28:22 +0000481.. _sqlite3-cursor-objects:
482
483Cursor Objects
484--------------
485
Georg Brandl96115fb22010-10-17 09:33:24 +0000486.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000487
Georg Brandl96115fb22010-10-17 09:33:24 +0000488 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000489
R David Murray6db23352012-09-30 20:44:43 -0400490 .. method:: execute(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000491
R David Murray6db23352012-09-30 20:44:43 -0400492 Executes an SQL statement. The SQL statement may be parametrized (i. e.
493 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
494 kinds of placeholders: question marks (qmark style) and named placeholders
495 (named style).
Georg Brandl116aa622007-08-15 14:28:22 +0000496
R David Murray6db23352012-09-30 20:44:43 -0400497 Here's an example of both styles:
Georg Brandl116aa622007-08-15 14:28:22 +0000498
R David Murray6db23352012-09-30 20:44:43 -0400499 .. literalinclude:: ../includes/sqlite3/execute_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000500
R David Murray6db23352012-09-30 20:44:43 -0400501 :meth:`execute` will only execute a single SQL statement. If you try to execute
502 more than one statement with it, it will raise a Warning. Use
503 :meth:`executescript` if you want to execute multiple SQL statements with one
504 call.
Georg Brandl116aa622007-08-15 14:28:22 +0000505
506
R David Murray6db23352012-09-30 20:44:43 -0400507 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl116aa622007-08-15 14:28:22 +0000508
R David Murray6db23352012-09-30 20:44:43 -0400509 Executes an SQL command against all parameter sequences or mappings found in
510 the sequence *sql*. The :mod:`sqlite3` module also allows using an
511 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000512
R David Murray6db23352012-09-30 20:44:43 -0400513 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000514
R David Murray6db23352012-09-30 20:44:43 -0400515 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000516
R David Murray6db23352012-09-30 20:44:43 -0400517 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl116aa622007-08-15 14:28:22 +0000518
519
R David Murray6db23352012-09-30 20:44:43 -0400520 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000521
R David Murray6db23352012-09-30 20:44:43 -0400522 This is a nonstandard convenience method for executing multiple SQL statements
523 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
524 gets as a parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
R David Murray6db23352012-09-30 20:44:43 -0400526 *sql_script* can be an instance of :class:`str` or :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000527
R David Murray6db23352012-09-30 20:44:43 -0400528 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000529
R David Murray6db23352012-09-30 20:44:43 -0400530 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532
R David Murray6db23352012-09-30 20:44:43 -0400533 .. method:: fetchone()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000534
R David Murray6db23352012-09-30 20:44:43 -0400535 Fetches the next row of a query result set, returning a single sequence,
536 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000537
538
R David Murray6db23352012-09-30 20:44:43 -0400539 .. method:: fetchmany(size=cursor.arraysize)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000540
R David Murray6db23352012-09-30 20:44:43 -0400541 Fetches the next set of rows of a query result, returning a list. An empty
542 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000543
R David Murray6db23352012-09-30 20:44:43 -0400544 The number of rows to fetch per call is specified by the *size* parameter.
545 If it is not given, the cursor's arraysize determines the number of rows
546 to be fetched. The method should try to fetch as many rows as indicated by
547 the size parameter. If this is not possible due to the specified number of
548 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000549
R David Murray6db23352012-09-30 20:44:43 -0400550 Note there are performance considerations involved with the *size* parameter.
551 For optimal performance, it is usually best to use the arraysize attribute.
552 If the *size* parameter is used, then it is best for it to retain the same
553 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000554
R David Murray6db23352012-09-30 20:44:43 -0400555 .. method:: fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000556
R David Murray6db23352012-09-30 20:44:43 -0400557 Fetches all (remaining) rows of a query result, returning a list. Note that
558 the cursor's arraysize attribute can affect the performance of this operation.
559 An empty list is returned when no rows are available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000560
561
R David Murray6db23352012-09-30 20:44:43 -0400562 .. attribute:: rowcount
Georg Brandl116aa622007-08-15 14:28:22 +0000563
R David Murray6db23352012-09-30 20:44:43 -0400564 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
565 attribute, the database engine's own support for the determination of "rows
566 affected"/"rows selected" is quirky.
Georg Brandl116aa622007-08-15 14:28:22 +0000567
R David Murray6db23352012-09-30 20:44:43 -0400568 For :meth:`executemany` statements, the number of modifications are summed up
569 into :attr:`rowcount`.
Georg Brandl116aa622007-08-15 14:28:22 +0000570
R David Murray6db23352012-09-30 20:44:43 -0400571 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
572 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
573 last operation is not determinable by the interface". This includes ``SELECT``
574 statements because we cannot determine the number of rows a query produced
575 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000576
R David Murray6db23352012-09-30 20:44:43 -0400577 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
578 you make a ``DELETE FROM table`` without any condition.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000579
R David Murray6db23352012-09-30 20:44:43 -0400580 .. attribute:: lastrowid
Gerhard Häringd3372792008-03-29 19:13:55 +0000581
R David Murray6db23352012-09-30 20:44:43 -0400582 This read-only attribute provides the rowid of the last modified row. It is
583 only set if you issued a ``INSERT`` statement using the :meth:`execute`
584 method. For operations other than ``INSERT`` or when :meth:`executemany` is
585 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl116aa622007-08-15 14:28:22 +0000586
R David Murray6db23352012-09-30 20:44:43 -0400587 .. attribute:: description
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000588
R David Murray6db23352012-09-30 20:44:43 -0400589 This read-only attribute provides the column names of the last query. To
590 remain compatible with the Python DB API, it returns a 7-tuple for each
591 column where the last six items of each tuple are :const:`None`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000592
R David Murray6db23352012-09-30 20:44:43 -0400593 It is set for ``SELECT`` statements without any matching rows as well.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000594
595.. _sqlite3-row-objects:
596
597Row Objects
598-----------
599
600.. class:: Row
601
602 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000603 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000604 It tries to mimic a tuple in most of its features.
605
606 It supports mapping access by column name and index, iteration,
607 representation, equality testing and :func:`len`.
608
609 If two :class:`Row` objects have exactly the same columns and their
610 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000611
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000612 .. method:: keys
613
614 This method returns a tuple of column names. Immediately after a query,
615 it is the first member of each tuple in :attr:`Cursor.description`.
616
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000617Let's assume we initialize a table as in the example given above::
618
Senthil Kumaran946eb862011-07-03 10:17:22 -0700619 conn = sqlite3.connect(":memory:")
620 c = conn.cursor()
621 c.execute('''create table stocks
622 (date text, trans text, symbol text,
623 qty real, price real)''')
624 c.execute("""insert into stocks
625 values ('2006-01-05','BUY','RHAT',100,35.14)""")
626 conn.commit()
627 c.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000628
629Now we plug :class:`Row` in::
630
Senthil Kumaran946eb862011-07-03 10:17:22 -0700631 >>> conn.row_factory = sqlite3.Row
632 >>> c = conn.cursor()
633 >>> c.execute('select * from stocks')
634 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
635 >>> r = c.fetchone()
636 >>> type(r)
637 <class 'sqlite3.Row'>
638 >>> tuple(r)
639 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
640 >>> len(r)
641 5
642 >>> r[2]
643 'RHAT'
644 >>> r.keys()
645 ['date', 'trans', 'symbol', 'qty', 'price']
646 >>> r['qty']
647 100.0
648 >>> for member in r:
649 ... print(member)
650 ...
651 2006-01-05
652 BUY
653 RHAT
654 100.0
655 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000656
657
Georg Brandl116aa622007-08-15 14:28:22 +0000658.. _sqlite3-types:
659
660SQLite and Python types
661-----------------------
662
663
664Introduction
665^^^^^^^^^^^^
666
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000667SQLite natively supports the following types: ``NULL``, ``INTEGER``,
668``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000669
670The following Python types can thus be sent to SQLite without any problem:
671
Georg Brandlf6945182008-02-01 11:56:49 +0000672+-------------------------------+-------------+
673| Python type | SQLite type |
674+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000675| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000676+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000677| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000678+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000679| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000680+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000681| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000682+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000683| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000684+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000686
Georg Brandl116aa622007-08-15 14:28:22 +0000687This is how SQLite types are converted to Python types by default:
688
689+-------------+---------------------------------------------+
690| SQLite type | Python type |
691+=============+=============================================+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000692| ``NULL`` | :const:`None` |
Georg Brandl116aa622007-08-15 14:28:22 +0000693+-------------+---------------------------------------------+
Ezio Melottib5845052009-09-13 05:49:25 +0000694| ``INTEGER`` | :class:`int` |
Georg Brandl116aa622007-08-15 14:28:22 +0000695+-------------+---------------------------------------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000696| ``REAL`` | :class:`float` |
Georg Brandl116aa622007-08-15 14:28:22 +0000697+-------------+---------------------------------------------+
Georg Brandlf6945182008-02-01 11:56:49 +0000698| ``TEXT`` | depends on text_factory, str by default |
Georg Brandl116aa622007-08-15 14:28:22 +0000699+-------------+---------------------------------------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000700| ``BLOB`` | :class:`bytes` |
Georg Brandl116aa622007-08-15 14:28:22 +0000701+-------------+---------------------------------------------+
702
703The type system of the :mod:`sqlite3` module is extensible in two ways: you can
704store additional Python types in a SQLite database via object adaptation, and
705you can let the :mod:`sqlite3` module convert SQLite types to different Python
706types via converters.
707
708
709Using adapters to store additional Python types in SQLite databases
710^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
711
712As described before, SQLite supports only a limited set of types natively. To
713use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000714sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000715str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000716
717The :mod:`sqlite3` module uses Python object adaptation, as described in
718:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
719
720There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
721type to one of the supported ones.
722
723
724Letting your object adapt itself
725""""""""""""""""""""""""""""""""
726
727This is a good approach if you write the class yourself. Let's suppose you have
728a class like this::
729
Éric Araujo28053fb2010-11-22 03:09:19 +0000730 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000731 def __init__(self, x, y):
732 self.x, self.y = x, y
733
734Now you want to store the point in a single SQLite column. First you'll have to
735choose one of the supported types first to be used for representing the point.
736Let's just use str and separate the coordinates using a semicolon. Then you need
737to give your class a method ``__conform__(self, protocol)`` which must return
738the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
739
740.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
741
742
743Registering an adapter callable
744"""""""""""""""""""""""""""""""
745
746The other possibility is to create a function that converts the type to the
747string representation and register the function with :meth:`register_adapter`.
748
Georg Brandl116aa622007-08-15 14:28:22 +0000749.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
750
751The :mod:`sqlite3` module has two default adapters for Python's built-in
752:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
753we want to store :class:`datetime.datetime` objects not in ISO representation,
754but as a Unix timestamp.
755
756.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
757
758
759Converting SQLite values to custom Python types
760^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
761
762Writing an adapter lets you send custom Python types to SQLite. But to make it
763really useful we need to make the Python to SQLite to Python roundtrip work.
764
765Enter converters.
766
767Let's go back to the :class:`Point` class. We stored the x and y coordinates
768separated via semicolons as strings in SQLite.
769
770First, we'll define a converter function that accepts the string as a parameter
771and constructs a :class:`Point` object from it.
772
773.. note::
774
775 Converter functions **always** get called with a string, no matter under which
776 data type you sent the value to SQLite.
777
Georg Brandl116aa622007-08-15 14:28:22 +0000778::
779
780 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200781 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +0000782 return Point(x, y)
783
784Now you need to make the :mod:`sqlite3` module know that what you select from
785the database is actually a point. There are two ways of doing this:
786
787* Implicitly via the declared type
788
789* Explicitly via the column name
790
791Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
792for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
793
794The following example illustrates both approaches.
795
796.. literalinclude:: ../includes/sqlite3/converter_point.py
797
798
799Default adapters and converters
800^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
801
802There are default adapters for the date and datetime types in the datetime
803module. They will be sent as ISO dates/ISO timestamps to SQLite.
804
805The default converters are registered under the name "date" for
806:class:`datetime.date` and under the name "timestamp" for
807:class:`datetime.datetime`.
808
809This way, you can use date/timestamps from Python without any additional
810fiddling in most cases. The format of the adapters is also compatible with the
811experimental SQLite date/time functions.
812
813The following example demonstrates this.
814
815.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
816
817
818.. _sqlite3-controlling-transactions:
819
820Controlling Transactions
821------------------------
822
823By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandl48310cd2009-01-03 21:18:54 +0000824Data Modification Language (DML) statement (i.e.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000825``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
826implicitly before a non-DML, non-query statement (i. e.
827anything other than ``SELECT`` or the aforementioned).
Georg Brandl116aa622007-08-15 14:28:22 +0000828
829So if you are within a transaction and issue a command like ``CREATE TABLE
830...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
831before executing that command. There are two reasons for doing that. The first
832is that some of these commands don't work within transactions. The other reason
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000833is that sqlite3 needs to keep track of the transaction state (if a transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000834is active or not). The current transaction state is exposed through the
835:attr:`Connection.in_transaction` attribute of the connection object.
Georg Brandl116aa622007-08-15 14:28:22 +0000836
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000837You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl116aa622007-08-15 14:28:22 +0000838(or none at all) via the *isolation_level* parameter to the :func:`connect`
839call, or via the :attr:`isolation_level` property of connections.
840
841If you want **autocommit mode**, then set :attr:`isolation_level` to None.
842
843Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandla971c652008-11-07 09:39:56 +0000844statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
845"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl116aa622007-08-15 14:28:22 +0000846
Georg Brandl116aa622007-08-15 14:28:22 +0000847
848
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000849Using :mod:`sqlite3` efficiently
850--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000851
852
853Using shortcut methods
854^^^^^^^^^^^^^^^^^^^^^^
855
856Using the nonstandard :meth:`execute`, :meth:`executemany` and
857:meth:`executescript` methods of the :class:`Connection` object, your code can
858be written more concisely because you don't have to create the (often
859superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
860objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000861objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +0000862directly using only a single call on the :class:`Connection` object.
863
864.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
865
866
867Accessing columns by name instead of by index
868^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
869
Georg Brandl22b34312009-07-26 14:54:51 +0000870One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000871:class:`sqlite3.Row` class designed to be used as a row factory.
872
873Rows wrapped with this class can be accessed both by index (like tuples) and
874case-insensitively by name:
875
876.. literalinclude:: ../includes/sqlite3/rowclass.py
877
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000878
879Using the connection as a context manager
880^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
881
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000882Connection objects can be used as context managers
883that automatically commit or rollback transactions. In the event of an
884exception, the transaction is rolled back; otherwise, the transaction is
885committed:
886
887.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +0000888
889
890Common issues
891-------------
892
893Multithreading
894^^^^^^^^^^^^^^
895
896Older SQLite versions had issues with sharing connections between threads.
897That's why the Python module disallows sharing connections and cursors between
898threads. If you still try to do so, you will get an exception at runtime.
899
900The only exception is calling the :meth:`~Connection.interrupt` method, which
901only makes sense to call from a different thread.
902
Gerhard Häringe0941c52010-10-03 21:47:06 +0000903.. rubric:: Footnotes
904
905.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumaran946eb862011-07-03 10:17:22 -0700906 default, because some platforms (notably Mac OS X) have SQLite
907 libraries which are compiled without this feature. To get loadable
908 extension support, you must pass --enable-loadable-sqlite-extensions to
909 configure.