blob: 08e3a2e0effe39f14e4a84981ac35f78af35998f [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
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +010021:file:`example.db` file::
Georg Brandl116aa622007-08-15 14:28:22 +000022
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020023 import sqlite3
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +010024 conn = sqlite3.connect('example.db')
Georg Brandl116aa622007-08-15 14:28:22 +000025
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
Georg Brandl116aa622007-08-15 14:28:22 +0000382
R David Murray6db23352012-09-30 20:44:43 -0400383 .. method:: set_progress_handler(handler, n)
Georg Brandl116aa622007-08-15 14:28:22 +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
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000393
R David Murray842ca5f2012-09-30 20:49:19 -0400394 .. method:: set_trace_callback(trace_callback)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000395
R David Murray842ca5f2012-09-30 20:49:19 -0400396 Registers *trace_callback* to be called for each SQL statement that is
397 actually executed by the SQLite backend.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200398
R David Murray842ca5f2012-09-30 20:49:19 -0400399 The only argument passed to the callback is the statement (as string) that
400 is being executed. The return value of the callback is ignored. Note that
401 the backend does not only run statements passed to the :meth:`Cursor.execute`
402 methods. Other sources include the transaction management of the Python
403 module and the execution of triggers defined in the current database.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200404
R David Murray842ca5f2012-09-30 20:49:19 -0400405 Passing :const:`None` as *trace_callback* will disable the trace callback.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200406
R David Murray842ca5f2012-09-30 20:49:19 -0400407 .. versionadded:: 3.3
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200408
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200409
R David Murray6db23352012-09-30 20:44:43 -0400410 .. method:: enable_load_extension(enabled)
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200411
R David Murray6db23352012-09-30 20:44:43 -0400412 This routine allows/disallows the SQLite engine to load SQLite extensions
413 from shared libraries. SQLite extensions can define new functions,
414 aggregates or whole new virtual table implementations. One well-known
415 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000416
R David Murray6db23352012-09-30 20:44:43 -0400417 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000418
R David Murray6db23352012-09-30 20:44:43 -0400419 .. versionadded:: 3.2
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200420
R David Murray6db23352012-09-30 20:44:43 -0400421 .. literalinclude:: ../includes/sqlite3/load_extension.py
Georg Brandl67b21b72010-08-17 15:07:14 +0000422
R David Murray6db23352012-09-30 20:44:43 -0400423 .. method:: load_extension(path)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000424
R David Murray6db23352012-09-30 20:44:43 -0400425 This routine loads a SQLite extension from a shared library. You have to
426 enable extension loading with :meth:`enable_load_extension` before you can
427 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000428
R David Murray6db23352012-09-30 20:44:43 -0400429 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000430
R David Murray6db23352012-09-30 20:44:43 -0400431 .. versionadded:: 3.2
Gerhard Häringe0941c52010-10-03 21:47:06 +0000432
R David Murray6db23352012-09-30 20:44:43 -0400433 .. attribute:: row_factory
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200434
R David Murray6db23352012-09-30 20:44:43 -0400435 You can change this attribute to a callable that accepts the cursor and the
436 original row as a tuple and will return the real result row. This way, you can
437 implement more advanced ways of returning results, such as returning an object
438 that can also access columns by name.
Georg Brandl116aa622007-08-15 14:28:22 +0000439
R David Murray6db23352012-09-30 20:44:43 -0400440 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000441
R David Murray6db23352012-09-30 20:44:43 -0400442 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000443
R David Murray6db23352012-09-30 20:44:43 -0400444 If returning a tuple doesn't suffice and you want name-based access to
445 columns, you should consider setting :attr:`row_factory` to the
446 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
447 index-based and case-insensitive name-based access to columns with almost no
448 memory overhead. It will probably be better than your own custom
449 dictionary-based approach or even a db_row based solution.
Georg Brandl116aa622007-08-15 14:28:22 +0000450
R David Murray6db23352012-09-30 20:44:43 -0400451 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000452
Georg Brandl116aa622007-08-15 14:28:22 +0000453
R David Murray6db23352012-09-30 20:44:43 -0400454 .. attribute:: text_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000455
R David Murray6db23352012-09-30 20:44:43 -0400456 Using this attribute you can control what objects are returned for the ``TEXT``
457 data type. By default, this attribute is set to :class:`str` and the
458 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
459 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000460
R David Murray6db23352012-09-30 20:44:43 -0400461 For efficiency reasons, there's also a way to return :class:`str` objects
462 only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
463 this attribute to :const:`sqlite3.OptimizedUnicode`.
Georg Brandl116aa622007-08-15 14:28:22 +0000464
R David Murray6db23352012-09-30 20:44:43 -0400465 You can also set it to any other callable that accepts a single bytestring
466 parameter and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000467
R David Murray6db23352012-09-30 20:44:43 -0400468 See the following example code for illustration:
Georg Brandl116aa622007-08-15 14:28:22 +0000469
R David Murray6db23352012-09-30 20:44:43 -0400470 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472
R David Murray6db23352012-09-30 20:44:43 -0400473 .. attribute:: total_changes
Georg Brandl116aa622007-08-15 14:28:22 +0000474
R David Murray6db23352012-09-30 20:44:43 -0400475 Returns the total number of database rows that have been modified, inserted, or
476 deleted since the database connection was opened.
Georg Brandl116aa622007-08-15 14:28:22 +0000477
478
R David Murray6db23352012-09-30 20:44:43 -0400479 .. attribute:: iterdump
Christian Heimesbbe741d2008-03-28 10:53:29 +0000480
R David Murray6db23352012-09-30 20:44:43 -0400481 Returns an iterator to dump the database in an SQL text format. Useful when
482 saving an in-memory database for later restoration. This function provides
483 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
484 shell.
Christian Heimesbbe741d2008-03-28 10:53:29 +0000485
R David Murray6db23352012-09-30 20:44:43 -0400486 Example::
Christian Heimesbbe741d2008-03-28 10:53:29 +0000487
R David Murray6db23352012-09-30 20:44:43 -0400488 # Convert file existing_db.db to SQL dump file dump.sql
489 import sqlite3, os
Christian Heimesbbe741d2008-03-28 10:53:29 +0000490
R David Murray6db23352012-09-30 20:44:43 -0400491 con = sqlite3.connect('existing_db.db')
492 with open('dump.sql', 'w') as f:
493 for line in con.iterdump():
494 f.write('%s\n' % line)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000495
496
Georg Brandl116aa622007-08-15 14:28:22 +0000497.. _sqlite3-cursor-objects:
498
499Cursor Objects
500--------------
501
Georg Brandl96115fb22010-10-17 09:33:24 +0000502.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000503
Georg Brandl96115fb22010-10-17 09:33:24 +0000504 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000505
R David Murray6db23352012-09-30 20:44:43 -0400506 .. method:: execute(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000507
R David Murray6db23352012-09-30 20:44:43 -0400508 Executes an SQL statement. The SQL statement may be parametrized (i. e.
509 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
510 kinds of placeholders: question marks (qmark style) and named placeholders
511 (named style).
Georg Brandl116aa622007-08-15 14:28:22 +0000512
R David Murray6db23352012-09-30 20:44:43 -0400513 Here's an example of both styles:
Georg Brandl116aa622007-08-15 14:28:22 +0000514
R David Murray6db23352012-09-30 20:44:43 -0400515 .. literalinclude:: ../includes/sqlite3/execute_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000516
R David Murray6db23352012-09-30 20:44:43 -0400517 :meth:`execute` will only execute a single SQL statement. If you try to execute
518 more than one statement with it, it will raise a Warning. Use
519 :meth:`executescript` if you want to execute multiple SQL statements with one
520 call.
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522
R David Murray6db23352012-09-30 20:44:43 -0400523 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl116aa622007-08-15 14:28:22 +0000524
R David Murray6db23352012-09-30 20:44:43 -0400525 Executes an SQL command against all parameter sequences or mappings found in
526 the sequence *sql*. The :mod:`sqlite3` module also allows using an
527 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000528
R David Murray6db23352012-09-30 20:44:43 -0400529 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000530
R David Murray6db23352012-09-30 20:44:43 -0400531 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000532
R David Murray6db23352012-09-30 20:44:43 -0400533 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl116aa622007-08-15 14:28:22 +0000534
535
R David Murray6db23352012-09-30 20:44:43 -0400536 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000537
R David Murray6db23352012-09-30 20:44:43 -0400538 This is a nonstandard convenience method for executing multiple SQL statements
539 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
540 gets as a parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
R David Murray6db23352012-09-30 20:44:43 -0400542 *sql_script* can be an instance of :class:`str` or :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000543
R David Murray6db23352012-09-30 20:44:43 -0400544 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000545
R David Murray6db23352012-09-30 20:44:43 -0400546 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl116aa622007-08-15 14:28:22 +0000547
548
R David Murray6db23352012-09-30 20:44:43 -0400549 .. method:: fetchone()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000550
R David Murray6db23352012-09-30 20:44:43 -0400551 Fetches the next row of a query result set, returning a single sequence,
552 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000553
554
R David Murray6db23352012-09-30 20:44:43 -0400555 .. method:: fetchmany(size=cursor.arraysize)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000556
R David Murray6db23352012-09-30 20:44:43 -0400557 Fetches the next set of rows of a query result, returning a list. An empty
558 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000559
R David Murray6db23352012-09-30 20:44:43 -0400560 The number of rows to fetch per call is specified by the *size* parameter.
561 If it is not given, the cursor's arraysize determines the number of rows
562 to be fetched. The method should try to fetch as many rows as indicated by
563 the size parameter. If this is not possible due to the specified number of
564 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000565
R David Murray6db23352012-09-30 20:44:43 -0400566 Note there are performance considerations involved with the *size* parameter.
567 For optimal performance, it is usually best to use the arraysize attribute.
568 If the *size* parameter is used, then it is best for it to retain the same
569 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000570
R David Murray6db23352012-09-30 20:44:43 -0400571 .. method:: fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000572
R David Murray6db23352012-09-30 20:44:43 -0400573 Fetches all (remaining) rows of a query result, returning a list. Note that
574 the cursor's arraysize attribute can affect the performance of this operation.
575 An empty list is returned when no rows are available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000576
577
R David Murray6db23352012-09-30 20:44:43 -0400578 .. attribute:: rowcount
Georg Brandl116aa622007-08-15 14:28:22 +0000579
R David Murray6db23352012-09-30 20:44:43 -0400580 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
581 attribute, the database engine's own support for the determination of "rows
582 affected"/"rows selected" is quirky.
Georg Brandl116aa622007-08-15 14:28:22 +0000583
R David Murray6db23352012-09-30 20:44:43 -0400584 For :meth:`executemany` statements, the number of modifications are summed up
585 into :attr:`rowcount`.
Georg Brandl116aa622007-08-15 14:28:22 +0000586
R David Murray6db23352012-09-30 20:44:43 -0400587 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
588 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
589 last operation is not determinable by the interface". This includes ``SELECT``
590 statements because we cannot determine the number of rows a query produced
591 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000592
R David Murray6db23352012-09-30 20:44:43 -0400593 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
594 you make a ``DELETE FROM table`` without any condition.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000595
R David Murray6db23352012-09-30 20:44:43 -0400596 .. attribute:: lastrowid
Gerhard Häringd3372792008-03-29 19:13:55 +0000597
R David Murray6db23352012-09-30 20:44:43 -0400598 This read-only attribute provides the rowid of the last modified row. It is
599 only set if you issued a ``INSERT`` statement using the :meth:`execute`
600 method. For operations other than ``INSERT`` or when :meth:`executemany` is
601 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl116aa622007-08-15 14:28:22 +0000602
R David Murray6db23352012-09-30 20:44:43 -0400603 .. attribute:: description
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000604
R David Murray6db23352012-09-30 20:44:43 -0400605 This read-only attribute provides the column names of the last query. To
606 remain compatible with the Python DB API, it returns a 7-tuple for each
607 column where the last six items of each tuple are :const:`None`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000608
R David Murray6db23352012-09-30 20:44:43 -0400609 It is set for ``SELECT`` statements without any matching rows as well.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000610
611.. _sqlite3-row-objects:
612
613Row Objects
614-----------
615
616.. class:: Row
617
618 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000619 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000620 It tries to mimic a tuple in most of its features.
621
622 It supports mapping access by column name and index, iteration,
623 representation, equality testing and :func:`len`.
624
625 If two :class:`Row` objects have exactly the same columns and their
626 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000627
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000628 .. method:: keys
629
630 This method returns a tuple of column names. Immediately after a query,
631 it is the first member of each tuple in :attr:`Cursor.description`.
632
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000633Let's assume we initialize a table as in the example given above::
634
Senthil Kumaran946eb862011-07-03 10:17:22 -0700635 conn = sqlite3.connect(":memory:")
636 c = conn.cursor()
637 c.execute('''create table stocks
638 (date text, trans text, symbol text,
639 qty real, price real)''')
640 c.execute("""insert into stocks
641 values ('2006-01-05','BUY','RHAT',100,35.14)""")
642 conn.commit()
643 c.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000644
645Now we plug :class:`Row` in::
646
Senthil Kumaran946eb862011-07-03 10:17:22 -0700647 >>> conn.row_factory = sqlite3.Row
648 >>> c = conn.cursor()
649 >>> c.execute('select * from stocks')
650 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
651 >>> r = c.fetchone()
652 >>> type(r)
653 <class 'sqlite3.Row'>
654 >>> tuple(r)
655 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
656 >>> len(r)
657 5
658 >>> r[2]
659 'RHAT'
660 >>> r.keys()
661 ['date', 'trans', 'symbol', 'qty', 'price']
662 >>> r['qty']
663 100.0
664 >>> for member in r:
665 ... print(member)
666 ...
667 2006-01-05
668 BUY
669 RHAT
670 100.0
671 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000672
673
Georg Brandl116aa622007-08-15 14:28:22 +0000674.. _sqlite3-types:
675
676SQLite and Python types
677-----------------------
678
679
680Introduction
681^^^^^^^^^^^^
682
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000683SQLite natively supports the following types: ``NULL``, ``INTEGER``,
684``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000685
686The following Python types can thus be sent to SQLite without any problem:
687
Georg Brandlf6945182008-02-01 11:56:49 +0000688+-------------------------------+-------------+
689| Python type | SQLite type |
690+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000691| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000692+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000693| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000694+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000695| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000696+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000697| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000698+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000699| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000700+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000702
Georg Brandl116aa622007-08-15 14:28:22 +0000703This is how SQLite types are converted to Python types by default:
704
705+-------------+---------------------------------------------+
706| SQLite type | Python type |
707+=============+=============================================+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000708| ``NULL`` | :const:`None` |
Georg Brandl116aa622007-08-15 14:28:22 +0000709+-------------+---------------------------------------------+
Ezio Melottib5845052009-09-13 05:49:25 +0000710| ``INTEGER`` | :class:`int` |
Georg Brandl116aa622007-08-15 14:28:22 +0000711+-------------+---------------------------------------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000712| ``REAL`` | :class:`float` |
Georg Brandl116aa622007-08-15 14:28:22 +0000713+-------------+---------------------------------------------+
Georg Brandlf6945182008-02-01 11:56:49 +0000714| ``TEXT`` | depends on text_factory, str by default |
Georg Brandl116aa622007-08-15 14:28:22 +0000715+-------------+---------------------------------------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000716| ``BLOB`` | :class:`bytes` |
Georg Brandl116aa622007-08-15 14:28:22 +0000717+-------------+---------------------------------------------+
718
719The type system of the :mod:`sqlite3` module is extensible in two ways: you can
720store additional Python types in a SQLite database via object adaptation, and
721you can let the :mod:`sqlite3` module convert SQLite types to different Python
722types via converters.
723
724
725Using adapters to store additional Python types in SQLite databases
726^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
727
728As described before, SQLite supports only a limited set of types natively. To
729use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000730sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000731str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000732
733The :mod:`sqlite3` module uses Python object adaptation, as described in
734:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
735
736There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
737type to one of the supported ones.
738
739
740Letting your object adapt itself
741""""""""""""""""""""""""""""""""
742
743This is a good approach if you write the class yourself. Let's suppose you have
744a class like this::
745
Éric Araujo28053fb2010-11-22 03:09:19 +0000746 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000747 def __init__(self, x, y):
748 self.x, self.y = x, y
749
750Now you want to store the point in a single SQLite column. First you'll have to
751choose one of the supported types first to be used for representing the point.
752Let's just use str and separate the coordinates using a semicolon. Then you need
753to give your class a method ``__conform__(self, protocol)`` which must return
754the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
755
756.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
757
758
759Registering an adapter callable
760"""""""""""""""""""""""""""""""
761
762The other possibility is to create a function that converts the type to the
763string representation and register the function with :meth:`register_adapter`.
764
Georg Brandl116aa622007-08-15 14:28:22 +0000765.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
766
767The :mod:`sqlite3` module has two default adapters for Python's built-in
768:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
769we want to store :class:`datetime.datetime` objects not in ISO representation,
770but as a Unix timestamp.
771
772.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
773
774
775Converting SQLite values to custom Python types
776^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
777
778Writing an adapter lets you send custom Python types to SQLite. But to make it
779really useful we need to make the Python to SQLite to Python roundtrip work.
780
781Enter converters.
782
783Let's go back to the :class:`Point` class. We stored the x and y coordinates
784separated via semicolons as strings in SQLite.
785
786First, we'll define a converter function that accepts the string as a parameter
787and constructs a :class:`Point` object from it.
788
789.. note::
790
791 Converter functions **always** get called with a string, no matter under which
792 data type you sent the value to SQLite.
793
Georg Brandl116aa622007-08-15 14:28:22 +0000794::
795
796 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200797 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +0000798 return Point(x, y)
799
800Now you need to make the :mod:`sqlite3` module know that what you select from
801the database is actually a point. There are two ways of doing this:
802
803* Implicitly via the declared type
804
805* Explicitly via the column name
806
807Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
808for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
809
810The following example illustrates both approaches.
811
812.. literalinclude:: ../includes/sqlite3/converter_point.py
813
814
815Default adapters and converters
816^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
817
818There are default adapters for the date and datetime types in the datetime
819module. They will be sent as ISO dates/ISO timestamps to SQLite.
820
821The default converters are registered under the name "date" for
822:class:`datetime.date` and under the name "timestamp" for
823:class:`datetime.datetime`.
824
825This way, you can use date/timestamps from Python without any additional
826fiddling in most cases. The format of the adapters is also compatible with the
827experimental SQLite date/time functions.
828
829The following example demonstrates this.
830
831.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
832
Petri Lehtinen5f794092013-02-26 21:32:02 +0200833If a timestamp stored in SQLite has a fractional part longer than 6
834numbers, its value will be truncated to microsecond precision by the
835timestamp converter.
836
Georg Brandl116aa622007-08-15 14:28:22 +0000837
838.. _sqlite3-controlling-transactions:
839
840Controlling Transactions
841------------------------
842
843By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandl48310cd2009-01-03 21:18:54 +0000844Data Modification Language (DML) statement (i.e.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000845``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
846implicitly before a non-DML, non-query statement (i. e.
847anything other than ``SELECT`` or the aforementioned).
Georg Brandl116aa622007-08-15 14:28:22 +0000848
849So if you are within a transaction and issue a command like ``CREATE TABLE
850...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
851before executing that command. There are two reasons for doing that. The first
852is that some of these commands don't work within transactions. The other reason
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000853is that sqlite3 needs to keep track of the transaction state (if a transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000854is active or not). The current transaction state is exposed through the
855:attr:`Connection.in_transaction` attribute of the connection object.
Georg Brandl116aa622007-08-15 14:28:22 +0000856
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000857You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl116aa622007-08-15 14:28:22 +0000858(or none at all) via the *isolation_level* parameter to the :func:`connect`
859call, or via the :attr:`isolation_level` property of connections.
860
861If you want **autocommit mode**, then set :attr:`isolation_level` to None.
862
863Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandla971c652008-11-07 09:39:56 +0000864statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
865"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl116aa622007-08-15 14:28:22 +0000866
Georg Brandl116aa622007-08-15 14:28:22 +0000867
868
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000869Using :mod:`sqlite3` efficiently
870--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000871
872
873Using shortcut methods
874^^^^^^^^^^^^^^^^^^^^^^
875
876Using the nonstandard :meth:`execute`, :meth:`executemany` and
877:meth:`executescript` methods of the :class:`Connection` object, your code can
878be written more concisely because you don't have to create the (often
879superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
880objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000881objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +0000882directly using only a single call on the :class:`Connection` object.
883
884.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
885
886
887Accessing columns by name instead of by index
888^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
889
Georg Brandl22b34312009-07-26 14:54:51 +0000890One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000891:class:`sqlite3.Row` class designed to be used as a row factory.
892
893Rows wrapped with this class can be accessed both by index (like tuples) and
894case-insensitively by name:
895
896.. literalinclude:: ../includes/sqlite3/rowclass.py
897
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000898
899Using the connection as a context manager
900^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
901
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000902Connection objects can be used as context managers
903that automatically commit or rollback transactions. In the event of an
904exception, the transaction is rolled back; otherwise, the transaction is
905committed:
906
907.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +0000908
909
910Common issues
911-------------
912
913Multithreading
914^^^^^^^^^^^^^^
915
916Older SQLite versions had issues with sharing connections between threads.
917That's why the Python module disallows sharing connections and cursors between
918threads. If you still try to do so, you will get an exception at runtime.
919
920The only exception is calling the :meth:`~Connection.interrupt` method, which
921only makes sense to call from a different thread.
922
Gerhard Häringe0941c52010-10-03 21:47:06 +0000923.. rubric:: Footnotes
924
925.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumaran946eb862011-07-03 10:17:22 -0700926 default, because some platforms (notably Mac OS X) have SQLite
927 libraries which are compiled without this feature. To get loadable
928 extension support, you must pass --enable-loadable-sqlite-extensions to
929 configure.