blob: 996e93eb77ea35a76ffdbbfcd959dc26ff0bddbd [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
Zachary Ware9d085622014-04-01 12:21:56 -050016The sqlite3 module was written by Gerhard Häring. It provides a SQL interface
17compliant with the DB-API 2.0 specification described by :pep:`249`.
Georg Brandl116aa622007-08-15 14:28:22 +000018
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
Zachary Ware9d085622014-04-01 12:21:56 -050034 c.execute('''CREATE TABLE stocks
35 (date text, trans text, symbol text, qty real, price real)''')
Georg Brandl116aa622007-08-15 14:28:22 +000036
37 # Insert a row of data
Zachary Ware9d085622014-04-01 12:21:56 -050038 c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
Georg Brandl116aa622007-08-15 14:28:22 +000039
40 # Save (commit) the changes
41 conn.commit()
42
Zachary Ware9d085622014-04-01 12:21:56 -050043 # We can also close the connection if we are done with it.
44 # Just be sure any changes have been committed or they will be lost.
45 conn.close()
46
47The data you've saved is persistent and is available in subsequent sessions::
48
49 import sqlite3
50 conn = sqlite3.connect('example.db')
51 c = conn.cursor()
Georg Brandl116aa622007-08-15 14:28:22 +000052
53Usually your SQL operations will need to use values from Python variables. You
54shouldn't assemble your query using Python's string operations because doing so
Zachary Ware9d085622014-04-01 12:21:56 -050055is insecure; it makes your program vulnerable to an SQL injection attack
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030056(see https://xkcd.com/327/ for humorous example of what can go wrong).
Georg Brandl116aa622007-08-15 14:28:22 +000057
58Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
59wherever you want to use a value, and then provide a tuple of values as the
Georg Brandl8a1e4c42009-05-25 21:13:36 +000060second argument to the cursor's :meth:`~Cursor.execute` method. (Other database
61modules may use a different placeholder, such as ``%s`` or ``:1``.) For
62example::
Georg Brandl116aa622007-08-15 14:28:22 +000063
64 # Never do this -- insecure!
Zachary Ware9d085622014-04-01 12:21:56 -050065 symbol = 'RHAT'
66 c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
Georg Brandl116aa622007-08-15 14:28:22 +000067
68 # Do this instead
Zachary Ware9d085622014-04-01 12:21:56 -050069 t = ('RHAT',)
70 c.execute('SELECT * FROM stocks WHERE symbol=?', t)
71 print(c.fetchone())
Georg Brandl116aa622007-08-15 14:28:22 +000072
Zachary Ware9d085622014-04-01 12:21:56 -050073 # Larger example that inserts many records at a time
74 purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
75 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
76 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
77 ]
78 c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
Georg Brandl116aa622007-08-15 14:28:22 +000079
Georg Brandl9afde1c2007-11-01 20:32:30 +000080To retrieve data after executing a SELECT statement, you can either treat the
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000081cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
82retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandl9afde1c2007-11-01 20:32:30 +000083matching rows.
Georg Brandl116aa622007-08-15 14:28:22 +000084
85This example uses the iterator form::
86
Zachary Ware9d085622014-04-01 12:21:56 -050087 >>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
88 print(row)
89
Ezio Melottib5845052009-09-13 05:49:25 +000090 ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
91 ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
92 ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
Zachary Ware9d085622014-04-01 12:21:56 -050093 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
Georg Brandl116aa622007-08-15 14:28:22 +000094
95
96.. seealso::
97
Benjamin Peterson216e47d2014-01-16 09:52:38 -050098 https://github.com/ghaering/pysqlite
Georg Brandl8a1e4c42009-05-25 21:13:36 +000099 The pysqlite web page -- sqlite3 is developed externally under the name
100 "pysqlite".
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300102 https://www.sqlite.org
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000103 The SQLite web page; the documentation describes the syntax and the
104 available data types for the supported SQL dialect.
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Zachary Ware9d085622014-04-01 12:21:56 -0500106 http://www.w3schools.com/sql/
107 Tutorial, reference and examples for learning SQL syntax.
108
Georg Brandl116aa622007-08-15 14:28:22 +0000109 :pep:`249` - Database API Specification 2.0
110 PEP written by Marc-André Lemburg.
111
112
113.. _sqlite3-module-contents:
114
115Module functions and constants
116------------------------------
117
118
R David Murray3f7beb92013-01-10 20:18:21 -0500119.. data:: version
120
121 The version number of this module, as a string. This is not the version of
122 the SQLite library.
123
124
125.. data:: version_info
126
127 The version number of this module, as a tuple of integers. This is not the
128 version of the SQLite library.
129
130
131.. data:: sqlite_version
132
133 The version number of the run-time SQLite library, as a string.
134
135
136.. data:: sqlite_version_info
137
138 The version number of the run-time SQLite library, as a tuple of integers.
139
140
Georg Brandl116aa622007-08-15 14:28:22 +0000141.. data:: PARSE_DECLTYPES
142
143 This constant is meant to be used with the *detect_types* parameter of the
144 :func:`connect` function.
145
146 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000147 column it returns. It will parse out the first word of the declared type,
148 i. e. for "integer primary key", it will parse out "integer", or for
149 "number(10)" it will parse out "number". Then for that column, it will look
150 into the converters dictionary and use the converter function registered for
151 that type there.
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153
154.. data:: PARSE_COLNAMES
155
156 This constant is meant to be used with the *detect_types* parameter of the
157 :func:`connect` function.
158
159 Setting this makes the SQLite interface parse the column name for each column it
160 returns. It will look for a string formed [mytype] in there, and then decide
161 that 'mytype' is the type of the column. It will try to find an entry of
162 'mytype' in the converters dictionary and then use the converter function found
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000163 there to return the value. The column name found in :attr:`Cursor.description`
Georg Brandl116aa622007-08-15 14:28:22 +0000164 is only the first word of the column name, i. e. if you use something like
165 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
166 first blank for the column name: the column name would simply be "x".
167
168
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100169.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171 Opens a connection to the SQLite database file *database*. You can use
172 ``":memory:"`` to open a database connection to a database that resides in RAM
173 instead of on disk.
174
175 When a database is accessed by multiple connections, and one of the processes
176 modifies the database, the SQLite database is locked until that transaction is
177 committed. The *timeout* parameter specifies how long the connection should wait
178 for the lock to go away until raising an exception. The default for the timeout
179 parameter is 5.0 (five seconds).
180
181 For the *isolation_level* parameter, please see the
182 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
183
Georg Brandl3c127112013-10-06 12:38:44 +0200184 SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
Georg Brandl116aa622007-08-15 14:28:22 +0000185 you want to use other types you must add support for them yourself. The
186 *detect_types* parameter and the using custom **converters** registered with the
187 module-level :func:`register_converter` function allow you to easily do that.
188
189 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
190 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
191 type detection on.
192
Senthil Kumaran7ee91942016-06-03 00:03:48 -0700193 By default, *check_same_thread* is :const:`True` and only the creating thread may
194 use the connection. If set :const:`False`, the returned connection may be shared
195 across multiple threads. When using multiple threads with the same connection
196 writing operations should be serialized by the user to avoid data corruption.
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
199 connect call. You can, however, subclass the :class:`Connection` class and make
200 :func:`connect` use your class instead by providing your class for the *factory*
201 parameter.
202
203 Consult the section :ref:`sqlite3-types` of this manual for details.
204
205 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
206 overhead. If you want to explicitly set the number of statements that are cached
207 for the connection, you can set the *cached_statements* parameter. The currently
208 implemented default is to cache 100 statements.
209
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100210 If *uri* is true, *database* is interpreted as a URI. This allows you
211 to specify options. For example, to open a database in read-only mode
212 you can use::
213
214 db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)
215
216 More information about this feature, including a list of recognized options, can
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300217 be found in the `SQLite URI documentation <https://www.sqlite.org/uri.html>`_.
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100218
219 .. versionchanged:: 3.4
220 Added the *uri* parameter.
221
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223.. function:: register_converter(typename, callable)
224
225 Registers a callable to convert a bytestring from the database into a custom
226 Python type. The callable will be invoked for all database values that are of
227 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
228 function for how the type detection works. Note that the case of *typename* and
229 the name of the type in your query must match!
230
231
232.. function:: register_adapter(type, callable)
233
234 Registers a callable to convert the custom Python type *type* into one of
235 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000236 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000237 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239
240.. function:: complete_statement(sql)
241
242 Returns :const:`True` if the string *sql* contains one or more complete SQL
243 statements terminated by semicolons. It does not verify that the SQL is
244 syntactically correct, only that there are no unclosed string literals and the
245 statement is terminated by a semicolon.
246
247 This can be used to build a shell for SQLite, as in the following example:
248
249
250 .. literalinclude:: ../includes/sqlite3/complete_statement.py
251
252
253.. function:: enable_callback_tracebacks(flag)
254
255 By default you will not get any tracebacks in user-defined functions,
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200256 aggregates, converters, authorizer callbacks etc. If you want to debug them,
257 you can call this function with *flag* set to ``True``. Afterwards, you will
258 get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to
259 disable the feature again.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261
262.. _sqlite3-connection-objects:
263
264Connection Objects
265------------------
266
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000267.. class:: Connection
268
269 A SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000270
R David Murray6db23352012-09-30 20:44:43 -0400271 .. attribute:: isolation_level
Georg Brandl116aa622007-08-15 14:28:22 +0000272
R David Murray6db23352012-09-30 20:44:43 -0400273 Get or set the current isolation level. :const:`None` for autocommit mode or
274 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
275 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000276
R David Murray6db23352012-09-30 20:44:43 -0400277 .. attribute:: in_transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000278
R David Murray6db23352012-09-30 20:44:43 -0400279 :const:`True` if a transaction is active (there are uncommitted changes),
280 :const:`False` otherwise. Read-only attribute.
R. David Murrayd35251d2010-06-01 01:32:12 +0000281
R David Murray6db23352012-09-30 20:44:43 -0400282 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000283
R David Murray6db23352012-09-30 20:44:43 -0400284 .. method:: cursor([cursorClass])
Georg Brandl116aa622007-08-15 14:28:22 +0000285
R David Murray6db23352012-09-30 20:44:43 -0400286 The cursor method accepts a single optional parameter *cursorClass*. If
287 supplied, this must be a custom cursor class that extends
288 :class:`sqlite3.Cursor`.
Georg Brandl116aa622007-08-15 14:28:22 +0000289
R David Murray6db23352012-09-30 20:44:43 -0400290 .. method:: commit()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000291
R David Murray6db23352012-09-30 20:44:43 -0400292 This method commits the current transaction. If you don't call this method,
293 anything you did since the last call to ``commit()`` is not visible from
294 other database connections. If you wonder why you don't see the data you've
295 written to the database, please check you didn't forget to call this method.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000296
R David Murray6db23352012-09-30 20:44:43 -0400297 .. method:: rollback()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000298
R David Murray6db23352012-09-30 20:44:43 -0400299 This method rolls back any changes to the database since the last call to
300 :meth:`commit`.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000301
R David Murray6db23352012-09-30 20:44:43 -0400302 .. method:: close()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000303
R David Murray6db23352012-09-30 20:44:43 -0400304 This closes the database connection. Note that this does not automatically
305 call :meth:`commit`. If you just close your database connection without
306 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000307
R David Murray6db23352012-09-30 20:44:43 -0400308 .. method:: execute(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000309
R David Murray6db23352012-09-30 20:44:43 -0400310 This is a nonstandard shortcut that creates an intermediate cursor object by
311 calling the cursor method, then calls the cursor's :meth:`execute
312 <Cursor.execute>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314
R David Murray6db23352012-09-30 20:44:43 -0400315 .. method:: executemany(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000316
R David Murray6db23352012-09-30 20:44:43 -0400317 This is a nonstandard shortcut that creates an intermediate cursor object by
318 calling the cursor method, then calls the cursor's :meth:`executemany
319 <Cursor.executemany>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000320
R David Murray6db23352012-09-30 20:44:43 -0400321 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000322
R David Murray6db23352012-09-30 20:44:43 -0400323 This is a nonstandard shortcut that creates an intermediate cursor object by
324 calling the cursor method, then calls the cursor's :meth:`executescript
325 <Cursor.executescript>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000326
327
R David Murray6db23352012-09-30 20:44:43 -0400328 .. method:: create_function(name, num_params, func)
Georg Brandl116aa622007-08-15 14:28:22 +0000329
R David Murray6db23352012-09-30 20:44:43 -0400330 Creates a user-defined function that you can later use from within SQL
331 statements under the function name *name*. *num_params* is the number of
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300332 parameters the function accepts (if *num_params* is -1, the function may
333 take any number of arguments), and *func* is a Python callable that is
334 called as the SQL function.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
R David Murray6db23352012-09-30 20:44:43 -0400336 The function can return any of the types supported by SQLite: bytes, str, int,
337 float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
R David Murray6db23352012-09-30 20:44:43 -0400339 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000340
R David Murray6db23352012-09-30 20:44:43 -0400341 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343
R David Murray6db23352012-09-30 20:44:43 -0400344 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl116aa622007-08-15 14:28:22 +0000345
R David Murray6db23352012-09-30 20:44:43 -0400346 Creates a user-defined aggregate function.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
R David Murray6db23352012-09-30 20:44:43 -0400348 The aggregate class must implement a ``step`` method, which accepts the number
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300349 of parameters *num_params* (if *num_params* is -1, the function may take
350 any number of arguments), and a ``finalize`` method which will return the
R David Murray6db23352012-09-30 20:44:43 -0400351 final result of the aggregate.
Georg Brandl116aa622007-08-15 14:28:22 +0000352
R David Murray6db23352012-09-30 20:44:43 -0400353 The ``finalize`` method can return any of the types supported by SQLite:
354 bytes, str, int, float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000355
R David Murray6db23352012-09-30 20:44:43 -0400356 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000357
R David Murray6db23352012-09-30 20:44:43 -0400358 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360
R David Murray6db23352012-09-30 20:44:43 -0400361 .. method:: create_collation(name, callable)
Georg Brandl116aa622007-08-15 14:28:22 +0000362
R David Murray6db23352012-09-30 20:44:43 -0400363 Creates a collation with the specified *name* and *callable*. The callable will
364 be passed two string arguments. It should return -1 if the first is ordered
365 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
366 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
367 your comparisons don't affect other SQL operations.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
R David Murray6db23352012-09-30 20:44:43 -0400369 Note that the callable will get its parameters as Python bytestrings, which will
370 normally be encoded in UTF-8.
Georg Brandl116aa622007-08-15 14:28:22 +0000371
R David Murray6db23352012-09-30 20:44:43 -0400372 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl116aa622007-08-15 14:28:22 +0000373
R David Murray6db23352012-09-30 20:44:43 -0400374 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl116aa622007-08-15 14:28:22 +0000375
R David Murray6db23352012-09-30 20:44:43 -0400376 To remove a collation, call ``create_collation`` with None as callable::
Georg Brandl116aa622007-08-15 14:28:22 +0000377
R David Murray6db23352012-09-30 20:44:43 -0400378 con.create_collation("reverse", None)
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380
R David Murray6db23352012-09-30 20:44:43 -0400381 .. method:: interrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000382
R David Murray6db23352012-09-30 20:44:43 -0400383 You can call this method from a different thread to abort any queries that might
384 be executing on the connection. The query will then abort and the caller will
385 get an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387
R David Murray6db23352012-09-30 20:44:43 -0400388 .. method:: set_authorizer(authorizer_callback)
Georg Brandl116aa622007-08-15 14:28:22 +0000389
R David Murray6db23352012-09-30 20:44:43 -0400390 This routine registers a callback. The callback is invoked for each attempt to
391 access a column of a table in the database. The callback should return
392 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
393 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
394 column should be treated as a NULL value. These constants are available in the
395 :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000396
R David Murray6db23352012-09-30 20:44:43 -0400397 The first argument to the callback signifies what kind of operation is to be
398 authorized. The second and third argument will be arguments or :const:`None`
399 depending on the first argument. The 4th argument is the name of the database
400 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
401 inner-most trigger or view that is responsible for the access attempt or
402 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl116aa622007-08-15 14:28:22 +0000403
R David Murray6db23352012-09-30 20:44:43 -0400404 Please consult the SQLite documentation about the possible values for the first
405 argument and the meaning of the second and third argument depending on the first
406 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000407
Georg Brandl116aa622007-08-15 14:28:22 +0000408
R David Murray6db23352012-09-30 20:44:43 -0400409 .. method:: set_progress_handler(handler, n)
Georg Brandl116aa622007-08-15 14:28:22 +0000410
R David Murray6db23352012-09-30 20:44:43 -0400411 This routine registers a callback. The callback is invoked for every *n*
412 instructions of the SQLite virtual machine. This is useful if you want to
413 get called from SQLite during long-running operations, for example to update
414 a GUI.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000415
R David Murray6db23352012-09-30 20:44:43 -0400416 If you want to clear any previously installed progress handler, call the
417 method with :const:`None` for *handler*.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000418
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000419
R David Murray842ca5f2012-09-30 20:49:19 -0400420 .. method:: set_trace_callback(trace_callback)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000421
R David Murray842ca5f2012-09-30 20:49:19 -0400422 Registers *trace_callback* to be called for each SQL statement that is
423 actually executed by the SQLite backend.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200424
R David Murray842ca5f2012-09-30 20:49:19 -0400425 The only argument passed to the callback is the statement (as string) that
426 is being executed. The return value of the callback is ignored. Note that
427 the backend does not only run statements passed to the :meth:`Cursor.execute`
428 methods. Other sources include the transaction management of the Python
429 module and the execution of triggers defined in the current database.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200430
R David Murray842ca5f2012-09-30 20:49:19 -0400431 Passing :const:`None` as *trace_callback* will disable the trace callback.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200432
R David Murray842ca5f2012-09-30 20:49:19 -0400433 .. versionadded:: 3.3
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200434
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200435
R David Murray6db23352012-09-30 20:44:43 -0400436 .. method:: enable_load_extension(enabled)
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200437
R David Murray6db23352012-09-30 20:44:43 -0400438 This routine allows/disallows the SQLite engine to load SQLite extensions
439 from shared libraries. SQLite extensions can define new functions,
440 aggregates or whole new virtual table implementations. One well-known
441 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000442
R David Murray6db23352012-09-30 20:44:43 -0400443 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000444
R David Murray6db23352012-09-30 20:44:43 -0400445 .. versionadded:: 3.2
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200446
R David Murray6db23352012-09-30 20:44:43 -0400447 .. literalinclude:: ../includes/sqlite3/load_extension.py
Georg Brandl67b21b72010-08-17 15:07:14 +0000448
R David Murray6db23352012-09-30 20:44:43 -0400449 .. method:: load_extension(path)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000450
R David Murray6db23352012-09-30 20:44:43 -0400451 This routine loads a SQLite extension from a shared library. You have to
452 enable extension loading with :meth:`enable_load_extension` before you can
453 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000454
R David Murray6db23352012-09-30 20:44:43 -0400455 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000456
R David Murray6db23352012-09-30 20:44:43 -0400457 .. versionadded:: 3.2
Gerhard Häringe0941c52010-10-03 21:47:06 +0000458
R David Murray6db23352012-09-30 20:44:43 -0400459 .. attribute:: row_factory
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200460
R David Murray6db23352012-09-30 20:44:43 -0400461 You can change this attribute to a callable that accepts the cursor and the
462 original row as a tuple and will return the real result row. This way, you can
463 implement more advanced ways of returning results, such as returning an object
464 that can also access columns by name.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
R David Murray6db23352012-09-30 20:44:43 -0400466 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000467
R David Murray6db23352012-09-30 20:44:43 -0400468 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000469
R David Murray6db23352012-09-30 20:44:43 -0400470 If returning a tuple doesn't suffice and you want name-based access to
471 columns, you should consider setting :attr:`row_factory` to the
472 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
473 index-based and case-insensitive name-based access to columns with almost no
474 memory overhead. It will probably be better than your own custom
475 dictionary-based approach or even a db_row based solution.
Georg Brandl116aa622007-08-15 14:28:22 +0000476
R David Murray6db23352012-09-30 20:44:43 -0400477 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000478
Georg Brandl116aa622007-08-15 14:28:22 +0000479
R David Murray6db23352012-09-30 20:44:43 -0400480 .. attribute:: text_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000481
R David Murray6db23352012-09-30 20:44:43 -0400482 Using this attribute you can control what objects are returned for the ``TEXT``
483 data type. By default, this attribute is set to :class:`str` and the
484 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
485 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000486
R David Murray6db23352012-09-30 20:44:43 -0400487 For efficiency reasons, there's also a way to return :class:`str` objects
488 only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
489 this attribute to :const:`sqlite3.OptimizedUnicode`.
Georg Brandl116aa622007-08-15 14:28:22 +0000490
R David Murray6db23352012-09-30 20:44:43 -0400491 You can also set it to any other callable that accepts a single bytestring
492 parameter and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000493
R David Murray6db23352012-09-30 20:44:43 -0400494 See the following example code for illustration:
Georg Brandl116aa622007-08-15 14:28:22 +0000495
R David Murray6db23352012-09-30 20:44:43 -0400496 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498
R David Murray6db23352012-09-30 20:44:43 -0400499 .. attribute:: total_changes
Georg Brandl116aa622007-08-15 14:28:22 +0000500
R David Murray6db23352012-09-30 20:44:43 -0400501 Returns the total number of database rows that have been modified, inserted, or
502 deleted since the database connection was opened.
Georg Brandl116aa622007-08-15 14:28:22 +0000503
504
Berker Peksag557a0632016-03-27 18:46:18 +0300505 .. method:: iterdump
Christian Heimesbbe741d2008-03-28 10:53:29 +0000506
R David Murray6db23352012-09-30 20:44:43 -0400507 Returns an iterator to dump the database in an SQL text format. Useful when
508 saving an in-memory database for later restoration. This function provides
509 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
510 shell.
Christian Heimesbbe741d2008-03-28 10:53:29 +0000511
R David Murray6db23352012-09-30 20:44:43 -0400512 Example::
Christian Heimesbbe741d2008-03-28 10:53:29 +0000513
R David Murray6db23352012-09-30 20:44:43 -0400514 # Convert file existing_db.db to SQL dump file dump.sql
Berker Peksag557a0632016-03-27 18:46:18 +0300515 import sqlite3
Christian Heimesbbe741d2008-03-28 10:53:29 +0000516
R David Murray6db23352012-09-30 20:44:43 -0400517 con = sqlite3.connect('existing_db.db')
518 with open('dump.sql', 'w') as f:
519 for line in con.iterdump():
520 f.write('%s\n' % line)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000521
522
Georg Brandl116aa622007-08-15 14:28:22 +0000523.. _sqlite3-cursor-objects:
524
525Cursor Objects
526--------------
527
Georg Brandl96115fb22010-10-17 09:33:24 +0000528.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Georg Brandl96115fb22010-10-17 09:33:24 +0000530 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000531
R David Murray6db23352012-09-30 20:44:43 -0400532 .. method:: execute(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000533
Zachary Ware9d085622014-04-01 12:21:56 -0500534 Executes an SQL statement. The SQL statement may be parameterized (i. e.
R David Murray6db23352012-09-30 20:44:43 -0400535 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
536 kinds of placeholders: question marks (qmark style) and named placeholders
537 (named style).
Georg Brandl116aa622007-08-15 14:28:22 +0000538
R David Murray6db23352012-09-30 20:44:43 -0400539 Here's an example of both styles:
Georg Brandl116aa622007-08-15 14:28:22 +0000540
R David Murray6db23352012-09-30 20:44:43 -0400541 .. literalinclude:: ../includes/sqlite3/execute_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000542
R David Murray6db23352012-09-30 20:44:43 -0400543 :meth:`execute` will only execute a single SQL statement. If you try to execute
544 more than one statement with it, it will raise a Warning. Use
545 :meth:`executescript` if you want to execute multiple SQL statements with one
546 call.
Georg Brandl116aa622007-08-15 14:28:22 +0000547
548
R David Murray6db23352012-09-30 20:44:43 -0400549 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl116aa622007-08-15 14:28:22 +0000550
R David Murray6db23352012-09-30 20:44:43 -0400551 Executes an SQL command against all parameter sequences or mappings found in
552 the sequence *sql*. The :mod:`sqlite3` module also allows using an
553 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000554
R David Murray6db23352012-09-30 20:44:43 -0400555 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000556
R David Murray6db23352012-09-30 20:44:43 -0400557 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000558
R David Murray6db23352012-09-30 20:44:43 -0400559 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561
R David Murray6db23352012-09-30 20:44:43 -0400562 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000563
R David Murray6db23352012-09-30 20:44:43 -0400564 This is a nonstandard convenience method for executing multiple SQL statements
565 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
566 gets as a parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000567
R David Murray6db23352012-09-30 20:44:43 -0400568 *sql_script* can be an instance of :class:`str` or :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000569
R David Murray6db23352012-09-30 20:44:43 -0400570 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000571
R David Murray6db23352012-09-30 20:44:43 -0400572 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl116aa622007-08-15 14:28:22 +0000573
574
R David Murray6db23352012-09-30 20:44:43 -0400575 .. method:: fetchone()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000576
R David Murray6db23352012-09-30 20:44:43 -0400577 Fetches the next row of a query result set, returning a single sequence,
578 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000579
580
R David Murray6db23352012-09-30 20:44:43 -0400581 .. method:: fetchmany(size=cursor.arraysize)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000582
R David Murray6db23352012-09-30 20:44:43 -0400583 Fetches the next set of rows of a query result, returning a list. An empty
584 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000585
R David Murray6db23352012-09-30 20:44:43 -0400586 The number of rows to fetch per call is specified by the *size* parameter.
587 If it is not given, the cursor's arraysize determines the number of rows
588 to be fetched. The method should try to fetch as many rows as indicated by
589 the size parameter. If this is not possible due to the specified number of
590 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000591
R David Murray6db23352012-09-30 20:44:43 -0400592 Note there are performance considerations involved with the *size* parameter.
593 For optimal performance, it is usually best to use the arraysize attribute.
594 If the *size* parameter is used, then it is best for it to retain the same
595 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000596
R David Murray6db23352012-09-30 20:44:43 -0400597 .. method:: fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000598
R David Murray6db23352012-09-30 20:44:43 -0400599 Fetches all (remaining) rows of a query result, returning a list. Note that
600 the cursor's arraysize attribute can affect the performance of this operation.
601 An empty list is returned when no rows are available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000602
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300603 .. method:: close()
604
605 Close the cursor now (rather than whenever ``__del__`` is called).
606
607 The cursor will be unusable from this point forward; a ``ProgrammingError``
608 exception will be raised if any operation is attempted with the cursor.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000609
R David Murray6db23352012-09-30 20:44:43 -0400610 .. attribute:: rowcount
Georg Brandl116aa622007-08-15 14:28:22 +0000611
R David Murray6db23352012-09-30 20:44:43 -0400612 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
613 attribute, the database engine's own support for the determination of "rows
614 affected"/"rows selected" is quirky.
Georg Brandl116aa622007-08-15 14:28:22 +0000615
R David Murray6db23352012-09-30 20:44:43 -0400616 For :meth:`executemany` statements, the number of modifications are summed up
617 into :attr:`rowcount`.
Georg Brandl116aa622007-08-15 14:28:22 +0000618
R David Murray6db23352012-09-30 20:44:43 -0400619 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
620 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
621 last operation is not determinable by the interface". This includes ``SELECT``
622 statements because we cannot determine the number of rows a query produced
623 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000624
R David Murray6db23352012-09-30 20:44:43 -0400625 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
626 you make a ``DELETE FROM table`` without any condition.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000627
R David Murray6db23352012-09-30 20:44:43 -0400628 .. attribute:: lastrowid
Gerhard Häringd3372792008-03-29 19:13:55 +0000629
R David Murray6db23352012-09-30 20:44:43 -0400630 This read-only attribute provides the rowid of the last modified row. It is
Martin Panter7462b6492015-11-02 03:37:02 +0000631 only set if you issued an ``INSERT`` statement using the :meth:`execute`
R David Murray6db23352012-09-30 20:44:43 -0400632 method. For operations other than ``INSERT`` or when :meth:`executemany` is
633 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl116aa622007-08-15 14:28:22 +0000634
R David Murray6db23352012-09-30 20:44:43 -0400635 .. attribute:: description
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000636
R David Murray6db23352012-09-30 20:44:43 -0400637 This read-only attribute provides the column names of the last query. To
638 remain compatible with the Python DB API, it returns a 7-tuple for each
639 column where the last six items of each tuple are :const:`None`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000640
R David Murray6db23352012-09-30 20:44:43 -0400641 It is set for ``SELECT`` statements without any matching rows as well.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000642
Ezio Melotti62564db2016-03-18 20:10:36 +0200643 .. attribute:: connection
644
645 This read-only attribute provides the SQLite database :class:`Connection`
646 used by the :class:`Cursor` object. A :class:`Cursor` object created by
647 calling :meth:`con.cursor() <Connection.cursor>` will have a
648 :attr:`connection` attribute that refers to *con*::
649
650 >>> con = sqlite3.connect(":memory:")
651 >>> cur = con.cursor()
652 >>> cur.connection == con
653 True
654
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000655.. _sqlite3-row-objects:
656
657Row Objects
658-----------
659
660.. class:: Row
661
662 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000663 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000664 It tries to mimic a tuple in most of its features.
665
666 It supports mapping access by column name and index, iteration,
667 representation, equality testing and :func:`len`.
668
669 If two :class:`Row` objects have exactly the same columns and their
670 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000671
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000672 .. method:: keys
673
R David Murray092135e2014-06-05 15:16:38 -0400674 This method returns a list of column names. Immediately after a query,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000675 it is the first member of each tuple in :attr:`Cursor.description`.
676
Serhiy Storchaka72e731c2015-03-31 13:33:11 +0300677 .. versionchanged:: 3.5
678 Added support of slicing.
679
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000680Let's assume we initialize a table as in the example given above::
681
Senthil Kumaran946eb862011-07-03 10:17:22 -0700682 conn = sqlite3.connect(":memory:")
683 c = conn.cursor()
684 c.execute('''create table stocks
685 (date text, trans text, symbol text,
686 qty real, price real)''')
687 c.execute("""insert into stocks
688 values ('2006-01-05','BUY','RHAT',100,35.14)""")
689 conn.commit()
690 c.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000691
692Now we plug :class:`Row` in::
693
Senthil Kumaran946eb862011-07-03 10:17:22 -0700694 >>> conn.row_factory = sqlite3.Row
695 >>> c = conn.cursor()
696 >>> c.execute('select * from stocks')
697 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
698 >>> r = c.fetchone()
699 >>> type(r)
700 <class 'sqlite3.Row'>
701 >>> tuple(r)
702 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
703 >>> len(r)
704 5
705 >>> r[2]
706 'RHAT'
707 >>> r.keys()
708 ['date', 'trans', 'symbol', 'qty', 'price']
709 >>> r['qty']
710 100.0
711 >>> for member in r:
712 ... print(member)
713 ...
714 2006-01-05
715 BUY
716 RHAT
717 100.0
718 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000719
720
Georg Brandl116aa622007-08-15 14:28:22 +0000721.. _sqlite3-types:
722
723SQLite and Python types
724-----------------------
725
726
727Introduction
728^^^^^^^^^^^^
729
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000730SQLite natively supports the following types: ``NULL``, ``INTEGER``,
731``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000732
733The following Python types can thus be sent to SQLite without any problem:
734
Georg Brandlf6945182008-02-01 11:56:49 +0000735+-------------------------------+-------------+
736| Python type | SQLite type |
737+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000738| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000739+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000740| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000741+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000742| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000743+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000744| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000745+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000746| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000747+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000748
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000749
Georg Brandl116aa622007-08-15 14:28:22 +0000750This is how SQLite types are converted to Python types by default:
751
Zachary Ware9d085622014-04-01 12:21:56 -0500752+-------------+----------------------------------------------+
753| SQLite type | Python type |
754+=============+==============================================+
755| ``NULL`` | :const:`None` |
756+-------------+----------------------------------------------+
757| ``INTEGER`` | :class:`int` |
758+-------------+----------------------------------------------+
759| ``REAL`` | :class:`float` |
760+-------------+----------------------------------------------+
761| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
762| | :class:`str` by default |
763+-------------+----------------------------------------------+
764| ``BLOB`` | :class:`bytes` |
765+-------------+----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000766
767The type system of the :mod:`sqlite3` module is extensible in two ways: you can
768store additional Python types in a SQLite database via object adaptation, and
769you can let the :mod:`sqlite3` module convert SQLite types to different Python
770types via converters.
771
772
773Using adapters to store additional Python types in SQLite databases
774^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
775
776As described before, SQLite supports only a limited set of types natively. To
777use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000778sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000779str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000780
Georg Brandl116aa622007-08-15 14:28:22 +0000781There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
782type to one of the supported ones.
783
784
785Letting your object adapt itself
786""""""""""""""""""""""""""""""""
787
788This is a good approach if you write the class yourself. Let's suppose you have
789a class like this::
790
Éric Araujo28053fb2010-11-22 03:09:19 +0000791 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000792 def __init__(self, x, y):
793 self.x, self.y = x, y
794
795Now you want to store the point in a single SQLite column. First you'll have to
796choose one of the supported types first to be used for representing the point.
797Let's just use str and separate the coordinates using a semicolon. Then you need
798to give your class a method ``__conform__(self, protocol)`` which must return
799the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
800
801.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
802
803
804Registering an adapter callable
805"""""""""""""""""""""""""""""""
806
807The other possibility is to create a function that converts the type to the
808string representation and register the function with :meth:`register_adapter`.
809
Georg Brandl116aa622007-08-15 14:28:22 +0000810.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
811
812The :mod:`sqlite3` module has two default adapters for Python's built-in
813:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
814we want to store :class:`datetime.datetime` objects not in ISO representation,
815but as a Unix timestamp.
816
817.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
818
819
820Converting SQLite values to custom Python types
821^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
822
823Writing an adapter lets you send custom Python types to SQLite. But to make it
824really useful we need to make the Python to SQLite to Python roundtrip work.
825
826Enter converters.
827
828Let's go back to the :class:`Point` class. We stored the x and y coordinates
829separated via semicolons as strings in SQLite.
830
831First, we'll define a converter function that accepts the string as a parameter
832and constructs a :class:`Point` object from it.
833
834.. note::
835
Zachary Ware9d085622014-04-01 12:21:56 -0500836 Converter functions **always** get called with a :class:`bytes` object, no
837 matter under which data type you sent the value to SQLite.
Georg Brandl116aa622007-08-15 14:28:22 +0000838
Georg Brandl116aa622007-08-15 14:28:22 +0000839::
840
841 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200842 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +0000843 return Point(x, y)
844
845Now you need to make the :mod:`sqlite3` module know that what you select from
846the database is actually a point. There are two ways of doing this:
847
848* Implicitly via the declared type
849
850* Explicitly via the column name
851
852Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
853for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
854
855The following example illustrates both approaches.
856
857.. literalinclude:: ../includes/sqlite3/converter_point.py
858
859
860Default adapters and converters
861^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
862
863There are default adapters for the date and datetime types in the datetime
864module. They will be sent as ISO dates/ISO timestamps to SQLite.
865
866The default converters are registered under the name "date" for
867:class:`datetime.date` and under the name "timestamp" for
868:class:`datetime.datetime`.
869
870This way, you can use date/timestamps from Python without any additional
871fiddling in most cases. The format of the adapters is also compatible with the
872experimental SQLite date/time functions.
873
874The following example demonstrates this.
875
876.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
877
Petri Lehtinen5f794092013-02-26 21:32:02 +0200878If a timestamp stored in SQLite has a fractional part longer than 6
879numbers, its value will be truncated to microsecond precision by the
880timestamp converter.
881
Georg Brandl116aa622007-08-15 14:28:22 +0000882
883.. _sqlite3-controlling-transactions:
884
885Controlling Transactions
886------------------------
887
888By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandl48310cd2009-01-03 21:18:54 +0000889Data Modification Language (DML) statement (i.e.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000890``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
891implicitly before a non-DML, non-query statement (i. e.
892anything other than ``SELECT`` or the aforementioned).
Georg Brandl116aa622007-08-15 14:28:22 +0000893
894So if you are within a transaction and issue a command like ``CREATE TABLE
895...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
896before executing that command. There are two reasons for doing that. The first
897is that some of these commands don't work within transactions. The other reason
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000898is that sqlite3 needs to keep track of the transaction state (if a transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000899is active or not). The current transaction state is exposed through the
900:attr:`Connection.in_transaction` attribute of the connection object.
Georg Brandl116aa622007-08-15 14:28:22 +0000901
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000902You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl116aa622007-08-15 14:28:22 +0000903(or none at all) via the *isolation_level* parameter to the :func:`connect`
904call, or via the :attr:`isolation_level` property of connections.
905
906If you want **autocommit mode**, then set :attr:`isolation_level` to None.
907
908Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandla971c652008-11-07 09:39:56 +0000909statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
910"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl116aa622007-08-15 14:28:22 +0000911
Georg Brandl116aa622007-08-15 14:28:22 +0000912
913
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000914Using :mod:`sqlite3` efficiently
915--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000916
917
918Using shortcut methods
919^^^^^^^^^^^^^^^^^^^^^^
920
921Using the nonstandard :meth:`execute`, :meth:`executemany` and
922:meth:`executescript` methods of the :class:`Connection` object, your code can
923be written more concisely because you don't have to create the (often
924superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
925objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000926objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +0000927directly using only a single call on the :class:`Connection` object.
928
929.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
930
931
932Accessing columns by name instead of by index
933^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
934
Georg Brandl22b34312009-07-26 14:54:51 +0000935One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000936:class:`sqlite3.Row` class designed to be used as a row factory.
937
938Rows wrapped with this class can be accessed both by index (like tuples) and
939case-insensitively by name:
940
941.. literalinclude:: ../includes/sqlite3/rowclass.py
942
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000943
944Using the connection as a context manager
945^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
946
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000947Connection objects can be used as context managers
948that automatically commit or rollback transactions. In the event of an
949exception, the transaction is rolled back; otherwise, the transaction is
950committed:
951
952.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +0000953
954
955Common issues
956-------------
957
958Multithreading
959^^^^^^^^^^^^^^
960
961Older SQLite versions had issues with sharing connections between threads.
962That's why the Python module disallows sharing connections and cursors between
963threads. If you still try to do so, you will get an exception at runtime.
964
965The only exception is calling the :meth:`~Connection.interrupt` method, which
966only makes sense to call from a different thread.
967
Gerhard Häringe0941c52010-10-03 21:47:06 +0000968.. rubric:: Footnotes
969
970.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumaran946eb862011-07-03 10:17:22 -0700971 default, because some platforms (notably Mac OS X) have SQLite
972 libraries which are compiled without this feature. To get loadable
973 extension support, you must pass --enable-loadable-sqlite-extensions to
974 configure.