blob: f6e538489ce0d37b0530d99c7e7058693b683462 [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
193 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
194 connect call. You can, however, subclass the :class:`Connection` class and make
195 :func:`connect` use your class instead by providing your class for the *factory*
196 parameter.
197
198 Consult the section :ref:`sqlite3-types` of this manual for details.
199
200 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
201 overhead. If you want to explicitly set the number of statements that are cached
202 for the connection, you can set the *cached_statements* parameter. The currently
203 implemented default is to cache 100 statements.
204
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100205 If *uri* is true, *database* is interpreted as a URI. This allows you
206 to specify options. For example, to open a database in read-only mode
207 you can use::
208
209 db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)
210
211 More information about this feature, including a list of recognized options, can
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300212 be found in the `SQLite URI documentation <https://www.sqlite.org/uri.html>`_.
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100213
214 .. versionchanged:: 3.4
215 Added the *uri* parameter.
216
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218.. function:: register_converter(typename, callable)
219
220 Registers a callable to convert a bytestring from the database into a custom
221 Python type. The callable will be invoked for all database values that are of
222 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
223 function for how the type detection works. Note that the case of *typename* and
224 the name of the type in your query must match!
225
226
227.. function:: register_adapter(type, callable)
228
229 Registers a callable to convert the custom Python type *type* into one of
230 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000231 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000232 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234
235.. function:: complete_statement(sql)
236
237 Returns :const:`True` if the string *sql* contains one or more complete SQL
238 statements terminated by semicolons. It does not verify that the SQL is
239 syntactically correct, only that there are no unclosed string literals and the
240 statement is terminated by a semicolon.
241
242 This can be used to build a shell for SQLite, as in the following example:
243
244
245 .. literalinclude:: ../includes/sqlite3/complete_statement.py
246
247
248.. function:: enable_callback_tracebacks(flag)
249
250 By default you will not get any tracebacks in user-defined functions,
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200251 aggregates, converters, authorizer callbacks etc. If you want to debug them,
252 you can call this function with *flag* set to ``True``. Afterwards, you will
253 get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to
254 disable the feature again.
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256
257.. _sqlite3-connection-objects:
258
259Connection Objects
260------------------
261
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000262.. class:: Connection
263
264 A SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000265
R David Murray6db23352012-09-30 20:44:43 -0400266 .. attribute:: isolation_level
Georg Brandl116aa622007-08-15 14:28:22 +0000267
R David Murray6db23352012-09-30 20:44:43 -0400268 Get or set the current isolation level. :const:`None` for autocommit mode or
269 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
270 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000271
R David Murray6db23352012-09-30 20:44:43 -0400272 .. attribute:: in_transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000273
R David Murray6db23352012-09-30 20:44:43 -0400274 :const:`True` if a transaction is active (there are uncommitted changes),
275 :const:`False` otherwise. Read-only attribute.
R. David Murrayd35251d2010-06-01 01:32:12 +0000276
R David Murray6db23352012-09-30 20:44:43 -0400277 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000278
R David Murray6db23352012-09-30 20:44:43 -0400279 .. method:: cursor([cursorClass])
Georg Brandl116aa622007-08-15 14:28:22 +0000280
R David Murray6db23352012-09-30 20:44:43 -0400281 The cursor method accepts a single optional parameter *cursorClass*. If
282 supplied, this must be a custom cursor class that extends
283 :class:`sqlite3.Cursor`.
Georg Brandl116aa622007-08-15 14:28:22 +0000284
R David Murray6db23352012-09-30 20:44:43 -0400285 .. method:: commit()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000286
R David Murray6db23352012-09-30 20:44:43 -0400287 This method commits the current transaction. If you don't call this method,
288 anything you did since the last call to ``commit()`` is not visible from
289 other database connections. If you wonder why you don't see the data you've
290 written to the database, please check you didn't forget to call this method.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000291
R David Murray6db23352012-09-30 20:44:43 -0400292 .. method:: rollback()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000293
R David Murray6db23352012-09-30 20:44:43 -0400294 This method rolls back any changes to the database since the last call to
295 :meth:`commit`.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000296
R David Murray6db23352012-09-30 20:44:43 -0400297 .. method:: close()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000298
R David Murray6db23352012-09-30 20:44:43 -0400299 This closes the database connection. Note that this does not automatically
300 call :meth:`commit`. If you just close your database connection without
301 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000302
R David Murray6db23352012-09-30 20:44:43 -0400303 .. method:: execute(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000304
R David Murray6db23352012-09-30 20:44:43 -0400305 This is a nonstandard shortcut that creates an intermediate cursor object by
306 calling the cursor method, then calls the cursor's :meth:`execute
307 <Cursor.execute>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309
R David Murray6db23352012-09-30 20:44:43 -0400310 .. method:: executemany(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000311
R David Murray6db23352012-09-30 20:44:43 -0400312 This is a nonstandard shortcut that creates an intermediate cursor object by
313 calling the cursor method, then calls the cursor's :meth:`executemany
314 <Cursor.executemany>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000315
R David Murray6db23352012-09-30 20:44:43 -0400316 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000317
R David Murray6db23352012-09-30 20:44:43 -0400318 This is a nonstandard shortcut that creates an intermediate cursor object by
319 calling the cursor method, then calls the cursor's :meth:`executescript
320 <Cursor.executescript>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000321
322
R David Murray6db23352012-09-30 20:44:43 -0400323 .. method:: create_function(name, num_params, func)
Georg Brandl116aa622007-08-15 14:28:22 +0000324
R David Murray6db23352012-09-30 20:44:43 -0400325 Creates a user-defined function that you can later use from within SQL
326 statements under the function name *name*. *num_params* is the number of
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300327 parameters the function accepts (if *num_params* is -1, the function may
328 take any number of arguments), and *func* is a Python callable that is
329 called as the SQL function.
Georg Brandl116aa622007-08-15 14:28:22 +0000330
R David Murray6db23352012-09-30 20:44:43 -0400331 The function can return any of the types supported by SQLite: bytes, str, int,
332 float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000333
R David Murray6db23352012-09-30 20:44:43 -0400334 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000335
R David Murray6db23352012-09-30 20:44:43 -0400336 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338
R David Murray6db23352012-09-30 20:44:43 -0400339 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl116aa622007-08-15 14:28:22 +0000340
R David Murray6db23352012-09-30 20:44:43 -0400341 Creates a user-defined aggregate function.
Georg Brandl116aa622007-08-15 14:28:22 +0000342
R David Murray6db23352012-09-30 20:44:43 -0400343 The aggregate class must implement a ``step`` method, which accepts the number
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300344 of parameters *num_params* (if *num_params* is -1, the function may take
345 any number of arguments), and a ``finalize`` method which will return the
R David Murray6db23352012-09-30 20:44:43 -0400346 final result of the aggregate.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
R David Murray6db23352012-09-30 20:44:43 -0400348 The ``finalize`` method can return any of the types supported by SQLite:
349 bytes, str, int, float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000350
R David Murray6db23352012-09-30 20:44:43 -0400351 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000352
R David Murray6db23352012-09-30 20:44:43 -0400353 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355
R David Murray6db23352012-09-30 20:44:43 -0400356 .. method:: create_collation(name, callable)
Georg Brandl116aa622007-08-15 14:28:22 +0000357
R David Murray6db23352012-09-30 20:44:43 -0400358 Creates a collation with the specified *name* and *callable*. The callable will
359 be passed two string arguments. It should return -1 if the first is ordered
360 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
361 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
362 your comparisons don't affect other SQL operations.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
R David Murray6db23352012-09-30 20:44:43 -0400364 Note that the callable will get its parameters as Python bytestrings, which will
365 normally be encoded in UTF-8.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
R David Murray6db23352012-09-30 20:44:43 -0400367 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl116aa622007-08-15 14:28:22 +0000368
R David Murray6db23352012-09-30 20:44:43 -0400369 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl116aa622007-08-15 14:28:22 +0000370
R David Murray6db23352012-09-30 20:44:43 -0400371 To remove a collation, call ``create_collation`` with None as callable::
Georg Brandl116aa622007-08-15 14:28:22 +0000372
R David Murray6db23352012-09-30 20:44:43 -0400373 con.create_collation("reverse", None)
Georg Brandl116aa622007-08-15 14:28:22 +0000374
375
R David Murray6db23352012-09-30 20:44:43 -0400376 .. method:: interrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000377
R David Murray6db23352012-09-30 20:44:43 -0400378 You can call this method from a different thread to abort any queries that might
379 be executing on the connection. The query will then abort and the caller will
380 get an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382
R David Murray6db23352012-09-30 20:44:43 -0400383 .. method:: set_authorizer(authorizer_callback)
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 each attempt to
386 access a column of a table in the database. The callback should return
387 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
388 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
389 column should be treated as a NULL value. These constants are available in the
390 :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000391
R David Murray6db23352012-09-30 20:44:43 -0400392 The first argument to the callback signifies what kind of operation is to be
393 authorized. The second and third argument will be arguments or :const:`None`
394 depending on the first argument. The 4th argument is the name of the database
395 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
396 inner-most trigger or view that is responsible for the access attempt or
397 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl116aa622007-08-15 14:28:22 +0000398
R David Murray6db23352012-09-30 20:44:43 -0400399 Please consult the SQLite documentation about the possible values for the first
400 argument and the meaning of the second and third argument depending on the first
401 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000402
Georg Brandl116aa622007-08-15 14:28:22 +0000403
R David Murray6db23352012-09-30 20:44:43 -0400404 .. method:: set_progress_handler(handler, n)
Georg Brandl116aa622007-08-15 14:28:22 +0000405
R David Murray6db23352012-09-30 20:44:43 -0400406 This routine registers a callback. The callback is invoked for every *n*
407 instructions of the SQLite virtual machine. This is useful if you want to
408 get called from SQLite during long-running operations, for example to update
409 a GUI.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000410
R David Murray6db23352012-09-30 20:44:43 -0400411 If you want to clear any previously installed progress handler, call the
412 method with :const:`None` for *handler*.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000413
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000414
R David Murray842ca5f2012-09-30 20:49:19 -0400415 .. method:: set_trace_callback(trace_callback)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000416
R David Murray842ca5f2012-09-30 20:49:19 -0400417 Registers *trace_callback* to be called for each SQL statement that is
418 actually executed by the SQLite backend.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200419
R David Murray842ca5f2012-09-30 20:49:19 -0400420 The only argument passed to the callback is the statement (as string) that
421 is being executed. The return value of the callback is ignored. Note that
422 the backend does not only run statements passed to the :meth:`Cursor.execute`
423 methods. Other sources include the transaction management of the Python
424 module and the execution of triggers defined in the current database.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200425
R David Murray842ca5f2012-09-30 20:49:19 -0400426 Passing :const:`None` as *trace_callback* will disable the trace callback.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200427
R David Murray842ca5f2012-09-30 20:49:19 -0400428 .. versionadded:: 3.3
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200429
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200430
R David Murray6db23352012-09-30 20:44:43 -0400431 .. method:: enable_load_extension(enabled)
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200432
R David Murray6db23352012-09-30 20:44:43 -0400433 This routine allows/disallows the SQLite engine to load SQLite extensions
434 from shared libraries. SQLite extensions can define new functions,
435 aggregates or whole new virtual table implementations. One well-known
436 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000437
R David Murray6db23352012-09-30 20:44:43 -0400438 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000439
R David Murray6db23352012-09-30 20:44:43 -0400440 .. versionadded:: 3.2
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200441
R David Murray6db23352012-09-30 20:44:43 -0400442 .. literalinclude:: ../includes/sqlite3/load_extension.py
Georg Brandl67b21b72010-08-17 15:07:14 +0000443
R David Murray6db23352012-09-30 20:44:43 -0400444 .. method:: load_extension(path)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000445
R David Murray6db23352012-09-30 20:44:43 -0400446 This routine loads a SQLite extension from a shared library. You have to
447 enable extension loading with :meth:`enable_load_extension` before you can
448 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000449
R David Murray6db23352012-09-30 20:44:43 -0400450 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000451
R David Murray6db23352012-09-30 20:44:43 -0400452 .. versionadded:: 3.2
Gerhard Häringe0941c52010-10-03 21:47:06 +0000453
R David Murray6db23352012-09-30 20:44:43 -0400454 .. attribute:: row_factory
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200455
R David Murray6db23352012-09-30 20:44:43 -0400456 You can change this attribute to a callable that accepts the cursor and the
457 original row as a tuple and will return the real result row. This way, you can
458 implement more advanced ways of returning results, such as returning an object
459 that can also access columns by name.
Georg Brandl116aa622007-08-15 14:28:22 +0000460
R David Murray6db23352012-09-30 20:44:43 -0400461 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000462
R David Murray6db23352012-09-30 20:44:43 -0400463 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000464
R David Murray6db23352012-09-30 20:44:43 -0400465 If returning a tuple doesn't suffice and you want name-based access to
466 columns, you should consider setting :attr:`row_factory` to the
467 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
468 index-based and case-insensitive name-based access to columns with almost no
469 memory overhead. It will probably be better than your own custom
470 dictionary-based approach or even a db_row based solution.
Georg Brandl116aa622007-08-15 14:28:22 +0000471
R David Murray6db23352012-09-30 20:44:43 -0400472 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000473
Georg Brandl116aa622007-08-15 14:28:22 +0000474
R David Murray6db23352012-09-30 20:44:43 -0400475 .. attribute:: text_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000476
R David Murray6db23352012-09-30 20:44:43 -0400477 Using this attribute you can control what objects are returned for the ``TEXT``
478 data type. By default, this attribute is set to :class:`str` and the
479 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
480 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000481
R David Murray6db23352012-09-30 20:44:43 -0400482 For efficiency reasons, there's also a way to return :class:`str` objects
483 only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
484 this attribute to :const:`sqlite3.OptimizedUnicode`.
Georg Brandl116aa622007-08-15 14:28:22 +0000485
R David Murray6db23352012-09-30 20:44:43 -0400486 You can also set it to any other callable that accepts a single bytestring
487 parameter and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000488
R David Murray6db23352012-09-30 20:44:43 -0400489 See the following example code for illustration:
Georg Brandl116aa622007-08-15 14:28:22 +0000490
R David Murray6db23352012-09-30 20:44:43 -0400491 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000492
493
R David Murray6db23352012-09-30 20:44:43 -0400494 .. attribute:: total_changes
Georg Brandl116aa622007-08-15 14:28:22 +0000495
R David Murray6db23352012-09-30 20:44:43 -0400496 Returns the total number of database rows that have been modified, inserted, or
497 deleted since the database connection was opened.
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499
Berker Peksag557a0632016-03-27 18:46:18 +0300500 .. method:: iterdump
Christian Heimesbbe741d2008-03-28 10:53:29 +0000501
R David Murray6db23352012-09-30 20:44:43 -0400502 Returns an iterator to dump the database in an SQL text format. Useful when
503 saving an in-memory database for later restoration. This function provides
504 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
505 shell.
Christian Heimesbbe741d2008-03-28 10:53:29 +0000506
R David Murray6db23352012-09-30 20:44:43 -0400507 Example::
Christian Heimesbbe741d2008-03-28 10:53:29 +0000508
R David Murray6db23352012-09-30 20:44:43 -0400509 # Convert file existing_db.db to SQL dump file dump.sql
Berker Peksag557a0632016-03-27 18:46:18 +0300510 import sqlite3
Christian Heimesbbe741d2008-03-28 10:53:29 +0000511
R David Murray6db23352012-09-30 20:44:43 -0400512 con = sqlite3.connect('existing_db.db')
513 with open('dump.sql', 'w') as f:
514 for line in con.iterdump():
515 f.write('%s\n' % line)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000516
517
Georg Brandl116aa622007-08-15 14:28:22 +0000518.. _sqlite3-cursor-objects:
519
520Cursor Objects
521--------------
522
Georg Brandl96115fb22010-10-17 09:33:24 +0000523.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000524
Georg Brandl96115fb22010-10-17 09:33:24 +0000525 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000526
R David Murray6db23352012-09-30 20:44:43 -0400527 .. method:: execute(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000528
Zachary Ware9d085622014-04-01 12:21:56 -0500529 Executes an SQL statement. The SQL statement may be parameterized (i. e.
R David Murray6db23352012-09-30 20:44:43 -0400530 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
531 kinds of placeholders: question marks (qmark style) and named placeholders
532 (named style).
Georg Brandl116aa622007-08-15 14:28:22 +0000533
R David Murray6db23352012-09-30 20:44:43 -0400534 Here's an example of both styles:
Georg Brandl116aa622007-08-15 14:28:22 +0000535
R David Murray6db23352012-09-30 20:44:43 -0400536 .. literalinclude:: ../includes/sqlite3/execute_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000537
R David Murray6db23352012-09-30 20:44:43 -0400538 :meth:`execute` will only execute a single SQL statement. If you try to execute
539 more than one statement with it, it will raise a Warning. Use
540 :meth:`executescript` if you want to execute multiple SQL statements with one
541 call.
Georg Brandl116aa622007-08-15 14:28:22 +0000542
543
R David Murray6db23352012-09-30 20:44:43 -0400544 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl116aa622007-08-15 14:28:22 +0000545
R David Murray6db23352012-09-30 20:44:43 -0400546 Executes an SQL command against all parameter sequences or mappings found in
547 the sequence *sql*. The :mod:`sqlite3` module also allows using an
548 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000549
R David Murray6db23352012-09-30 20:44:43 -0400550 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000551
R David Murray6db23352012-09-30 20:44:43 -0400552 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000553
R David Murray6db23352012-09-30 20:44:43 -0400554 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556
R David Murray6db23352012-09-30 20:44:43 -0400557 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000558
R David Murray6db23352012-09-30 20:44:43 -0400559 This is a nonstandard convenience method for executing multiple SQL statements
560 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
561 gets as a parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000562
R David Murray6db23352012-09-30 20:44:43 -0400563 *sql_script* can be an instance of :class:`str` or :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000564
R David Murray6db23352012-09-30 20:44:43 -0400565 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000566
R David Murray6db23352012-09-30 20:44:43 -0400567 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569
R David Murray6db23352012-09-30 20:44:43 -0400570 .. method:: fetchone()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000571
R David Murray6db23352012-09-30 20:44:43 -0400572 Fetches the next row of a query result set, returning a single sequence,
573 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000574
575
R David Murray6db23352012-09-30 20:44:43 -0400576 .. method:: fetchmany(size=cursor.arraysize)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000577
R David Murray6db23352012-09-30 20:44:43 -0400578 Fetches the next set of rows of a query result, returning a list. An empty
579 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000580
R David Murray6db23352012-09-30 20:44:43 -0400581 The number of rows to fetch per call is specified by the *size* parameter.
582 If it is not given, the cursor's arraysize determines the number of rows
583 to be fetched. The method should try to fetch as many rows as indicated by
584 the size parameter. If this is not possible due to the specified number of
585 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000586
R David Murray6db23352012-09-30 20:44:43 -0400587 Note there are performance considerations involved with the *size* parameter.
588 For optimal performance, it is usually best to use the arraysize attribute.
589 If the *size* parameter is used, then it is best for it to retain the same
590 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000591
R David Murray6db23352012-09-30 20:44:43 -0400592 .. method:: fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000593
R David Murray6db23352012-09-30 20:44:43 -0400594 Fetches all (remaining) rows of a query result, returning a list. Note that
595 the cursor's arraysize attribute can affect the performance of this operation.
596 An empty list is returned when no rows are available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000597
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300598 .. method:: close()
599
600 Close the cursor now (rather than whenever ``__del__`` is called).
601
602 The cursor will be unusable from this point forward; a ``ProgrammingError``
603 exception will be raised if any operation is attempted with the cursor.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000604
R David Murray6db23352012-09-30 20:44:43 -0400605 .. attribute:: rowcount
Georg Brandl116aa622007-08-15 14:28:22 +0000606
R David Murray6db23352012-09-30 20:44:43 -0400607 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
608 attribute, the database engine's own support for the determination of "rows
609 affected"/"rows selected" is quirky.
Georg Brandl116aa622007-08-15 14:28:22 +0000610
R David Murray6db23352012-09-30 20:44:43 -0400611 For :meth:`executemany` statements, the number of modifications are summed up
612 into :attr:`rowcount`.
Georg Brandl116aa622007-08-15 14:28:22 +0000613
R David Murray6db23352012-09-30 20:44:43 -0400614 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
615 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
616 last operation is not determinable by the interface". This includes ``SELECT``
617 statements because we cannot determine the number of rows a query produced
618 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000619
R David Murray6db23352012-09-30 20:44:43 -0400620 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
621 you make a ``DELETE FROM table`` without any condition.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000622
R David Murray6db23352012-09-30 20:44:43 -0400623 .. attribute:: lastrowid
Gerhard Häringd3372792008-03-29 19:13:55 +0000624
R David Murray6db23352012-09-30 20:44:43 -0400625 This read-only attribute provides the rowid of the last modified row. It is
Martin Panter7462b6492015-11-02 03:37:02 +0000626 only set if you issued an ``INSERT`` statement using the :meth:`execute`
R David Murray6db23352012-09-30 20:44:43 -0400627 method. For operations other than ``INSERT`` or when :meth:`executemany` is
628 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl116aa622007-08-15 14:28:22 +0000629
R David Murray6db23352012-09-30 20:44:43 -0400630 .. attribute:: description
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000631
R David Murray6db23352012-09-30 20:44:43 -0400632 This read-only attribute provides the column names of the last query. To
633 remain compatible with the Python DB API, it returns a 7-tuple for each
634 column where the last six items of each tuple are :const:`None`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000635
R David Murray6db23352012-09-30 20:44:43 -0400636 It is set for ``SELECT`` statements without any matching rows as well.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000637
Ezio Melotti62564db2016-03-18 20:10:36 +0200638 .. attribute:: connection
639
640 This read-only attribute provides the SQLite database :class:`Connection`
641 used by the :class:`Cursor` object. A :class:`Cursor` object created by
642 calling :meth:`con.cursor() <Connection.cursor>` will have a
643 :attr:`connection` attribute that refers to *con*::
644
645 >>> con = sqlite3.connect(":memory:")
646 >>> cur = con.cursor()
647 >>> cur.connection == con
648 True
649
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000650.. _sqlite3-row-objects:
651
652Row Objects
653-----------
654
655.. class:: Row
656
657 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000658 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000659 It tries to mimic a tuple in most of its features.
660
661 It supports mapping access by column name and index, iteration,
662 representation, equality testing and :func:`len`.
663
664 If two :class:`Row` objects have exactly the same columns and their
665 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000666
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000667 .. method:: keys
668
R David Murray092135e2014-06-05 15:16:38 -0400669 This method returns a list of column names. Immediately after a query,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000670 it is the first member of each tuple in :attr:`Cursor.description`.
671
Serhiy Storchaka72e731c2015-03-31 13:33:11 +0300672 .. versionchanged:: 3.5
673 Added support of slicing.
674
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000675Let's assume we initialize a table as in the example given above::
676
Senthil Kumaran946eb862011-07-03 10:17:22 -0700677 conn = sqlite3.connect(":memory:")
678 c = conn.cursor()
679 c.execute('''create table stocks
680 (date text, trans text, symbol text,
681 qty real, price real)''')
682 c.execute("""insert into stocks
683 values ('2006-01-05','BUY','RHAT',100,35.14)""")
684 conn.commit()
685 c.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000686
687Now we plug :class:`Row` in::
688
Senthil Kumaran946eb862011-07-03 10:17:22 -0700689 >>> conn.row_factory = sqlite3.Row
690 >>> c = conn.cursor()
691 >>> c.execute('select * from stocks')
692 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
693 >>> r = c.fetchone()
694 >>> type(r)
695 <class 'sqlite3.Row'>
696 >>> tuple(r)
697 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
698 >>> len(r)
699 5
700 >>> r[2]
701 'RHAT'
702 >>> r.keys()
703 ['date', 'trans', 'symbol', 'qty', 'price']
704 >>> r['qty']
705 100.0
706 >>> for member in r:
707 ... print(member)
708 ...
709 2006-01-05
710 BUY
711 RHAT
712 100.0
713 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000714
715
Georg Brandl116aa622007-08-15 14:28:22 +0000716.. _sqlite3-types:
717
718SQLite and Python types
719-----------------------
720
721
722Introduction
723^^^^^^^^^^^^
724
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000725SQLite natively supports the following types: ``NULL``, ``INTEGER``,
726``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000727
728The following Python types can thus be sent to SQLite without any problem:
729
Georg Brandlf6945182008-02-01 11:56:49 +0000730+-------------------------------+-------------+
731| Python type | SQLite type |
732+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000733| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000734+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000735| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000736+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000737| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000738+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000739| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000740+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000741| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000742+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000744
Georg Brandl116aa622007-08-15 14:28:22 +0000745This is how SQLite types are converted to Python types by default:
746
Zachary Ware9d085622014-04-01 12:21:56 -0500747+-------------+----------------------------------------------+
748| SQLite type | Python type |
749+=============+==============================================+
750| ``NULL`` | :const:`None` |
751+-------------+----------------------------------------------+
752| ``INTEGER`` | :class:`int` |
753+-------------+----------------------------------------------+
754| ``REAL`` | :class:`float` |
755+-------------+----------------------------------------------+
756| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
757| | :class:`str` by default |
758+-------------+----------------------------------------------+
759| ``BLOB`` | :class:`bytes` |
760+-------------+----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000761
762The type system of the :mod:`sqlite3` module is extensible in two ways: you can
763store additional Python types in a SQLite database via object adaptation, and
764you can let the :mod:`sqlite3` module convert SQLite types to different Python
765types via converters.
766
767
768Using adapters to store additional Python types in SQLite databases
769^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
770
771As described before, SQLite supports only a limited set of types natively. To
772use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000773sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000774str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000775
Georg Brandl116aa622007-08-15 14:28:22 +0000776There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
777type to one of the supported ones.
778
779
780Letting your object adapt itself
781""""""""""""""""""""""""""""""""
782
783This is a good approach if you write the class yourself. Let's suppose you have
784a class like this::
785
Éric Araujo28053fb2010-11-22 03:09:19 +0000786 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000787 def __init__(self, x, y):
788 self.x, self.y = x, y
789
790Now you want to store the point in a single SQLite column. First you'll have to
791choose one of the supported types first to be used for representing the point.
792Let's just use str and separate the coordinates using a semicolon. Then you need
793to give your class a method ``__conform__(self, protocol)`` which must return
794the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
795
796.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
797
798
799Registering an adapter callable
800"""""""""""""""""""""""""""""""
801
802The other possibility is to create a function that converts the type to the
803string representation and register the function with :meth:`register_adapter`.
804
Georg Brandl116aa622007-08-15 14:28:22 +0000805.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
806
807The :mod:`sqlite3` module has two default adapters for Python's built-in
808:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
809we want to store :class:`datetime.datetime` objects not in ISO representation,
810but as a Unix timestamp.
811
812.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
813
814
815Converting SQLite values to custom Python types
816^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
817
818Writing an adapter lets you send custom Python types to SQLite. But to make it
819really useful we need to make the Python to SQLite to Python roundtrip work.
820
821Enter converters.
822
823Let's go back to the :class:`Point` class. We stored the x and y coordinates
824separated via semicolons as strings in SQLite.
825
826First, we'll define a converter function that accepts the string as a parameter
827and constructs a :class:`Point` object from it.
828
829.. note::
830
Zachary Ware9d085622014-04-01 12:21:56 -0500831 Converter functions **always** get called with a :class:`bytes` object, no
832 matter under which data type you sent the value to SQLite.
Georg Brandl116aa622007-08-15 14:28:22 +0000833
Georg Brandl116aa622007-08-15 14:28:22 +0000834::
835
836 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200837 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +0000838 return Point(x, y)
839
840Now you need to make the :mod:`sqlite3` module know that what you select from
841the database is actually a point. There are two ways of doing this:
842
843* Implicitly via the declared type
844
845* Explicitly via the column name
846
847Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
848for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
849
850The following example illustrates both approaches.
851
852.. literalinclude:: ../includes/sqlite3/converter_point.py
853
854
855Default adapters and converters
856^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
857
858There are default adapters for the date and datetime types in the datetime
859module. They will be sent as ISO dates/ISO timestamps to SQLite.
860
861The default converters are registered under the name "date" for
862:class:`datetime.date` and under the name "timestamp" for
863:class:`datetime.datetime`.
864
865This way, you can use date/timestamps from Python without any additional
866fiddling in most cases. The format of the adapters is also compatible with the
867experimental SQLite date/time functions.
868
869The following example demonstrates this.
870
871.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
872
Petri Lehtinen5f794092013-02-26 21:32:02 +0200873If a timestamp stored in SQLite has a fractional part longer than 6
874numbers, its value will be truncated to microsecond precision by the
875timestamp converter.
876
Georg Brandl116aa622007-08-15 14:28:22 +0000877
878.. _sqlite3-controlling-transactions:
879
880Controlling Transactions
881------------------------
882
883By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandl48310cd2009-01-03 21:18:54 +0000884Data Modification Language (DML) statement (i.e.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000885``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
886implicitly before a non-DML, non-query statement (i. e.
887anything other than ``SELECT`` or the aforementioned).
Georg Brandl116aa622007-08-15 14:28:22 +0000888
889So if you are within a transaction and issue a command like ``CREATE TABLE
890...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
891before executing that command. There are two reasons for doing that. The first
892is that some of these commands don't work within transactions. The other reason
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000893is that sqlite3 needs to keep track of the transaction state (if a transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000894is active or not). The current transaction state is exposed through the
895:attr:`Connection.in_transaction` attribute of the connection object.
Georg Brandl116aa622007-08-15 14:28:22 +0000896
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000897You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl116aa622007-08-15 14:28:22 +0000898(or none at all) via the *isolation_level* parameter to the :func:`connect`
899call, or via the :attr:`isolation_level` property of connections.
900
901If you want **autocommit mode**, then set :attr:`isolation_level` to None.
902
903Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandla971c652008-11-07 09:39:56 +0000904statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
905"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl116aa622007-08-15 14:28:22 +0000906
Georg Brandl116aa622007-08-15 14:28:22 +0000907
908
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000909Using :mod:`sqlite3` efficiently
910--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000911
912
913Using shortcut methods
914^^^^^^^^^^^^^^^^^^^^^^
915
916Using the nonstandard :meth:`execute`, :meth:`executemany` and
917:meth:`executescript` methods of the :class:`Connection` object, your code can
918be written more concisely because you don't have to create the (often
919superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
920objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000921objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +0000922directly using only a single call on the :class:`Connection` object.
923
924.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
925
926
927Accessing columns by name instead of by index
928^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
929
Georg Brandl22b34312009-07-26 14:54:51 +0000930One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000931:class:`sqlite3.Row` class designed to be used as a row factory.
932
933Rows wrapped with this class can be accessed both by index (like tuples) and
934case-insensitively by name:
935
936.. literalinclude:: ../includes/sqlite3/rowclass.py
937
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000938
939Using the connection as a context manager
940^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
941
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000942Connection objects can be used as context managers
943that automatically commit or rollback transactions. In the event of an
944exception, the transaction is rolled back; otherwise, the transaction is
945committed:
946
947.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +0000948
949
950Common issues
951-------------
952
953Multithreading
954^^^^^^^^^^^^^^
955
956Older SQLite versions had issues with sharing connections between threads.
957That's why the Python module disallows sharing connections and cursors between
958threads. If you still try to do so, you will get an exception at runtime.
959
960The only exception is calling the :meth:`~Connection.interrupt` method, which
961only makes sense to call from a different thread.
962
Gerhard Häringe0941c52010-10-03 21:47:06 +0000963.. rubric:: Footnotes
964
965.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumaran946eb862011-07-03 10:17:22 -0700966 default, because some platforms (notably Mac OS X) have SQLite
967 libraries which are compiled without this feature. To get loadable
968 extension support, you must pass --enable-loadable-sqlite-extensions to
969 configure.