blob: 13aa8c512d03197da9aee7a63f198a115572bc01 [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.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +02007.. sectionauthor:: Gerhard Häring <gh@ghaering.de>
Georg Brandl116aa622007-08-15 14:28:22 +00008
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04009**Source code:** :source:`Lib/sqlite3/`
10
11--------------
Georg Brandl116aa622007-08-15 14:28:22 +000012
Georg Brandl116aa622007-08-15 14:28:22 +000013SQLite is a C library that provides a lightweight disk-based database that
14doesn't require a separate server process and allows accessing the database
15using a nonstandard variant of the SQL query language. Some applications can use
16SQLite for internal data storage. It's also possible to prototype an
17application using SQLite and then port the code to a larger database such as
18PostgreSQL or Oracle.
19
Zachary Ware9d085622014-04-01 12:21:56 -050020The sqlite3 module was written by Gerhard Häring. It provides a SQL interface
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +020021compliant with the DB-API 2.0 specification described by :pep:`249`, and
22requires SQLite 3.7.3 or newer.
Georg Brandl116aa622007-08-15 14:28:22 +000023
24To use the module, you must first create a :class:`Connection` object that
25represents the database. Here the data will be stored in the
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +010026:file:`example.db` file::
Georg Brandl116aa622007-08-15 14:28:22 +000027
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020028 import sqlite3
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +010029 conn = sqlite3.connect('example.db')
Georg Brandl116aa622007-08-15 14:28:22 +000030
31You can also supply the special name ``:memory:`` to create a database in RAM.
32
33Once you have a :class:`Connection`, you can create a :class:`Cursor` object
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000034and call its :meth:`~Cursor.execute` method to perform SQL commands::
Georg Brandl116aa622007-08-15 14:28:22 +000035
36 c = conn.cursor()
37
38 # Create table
Zachary Ware9d085622014-04-01 12:21:56 -050039 c.execute('''CREATE TABLE stocks
40 (date text, trans text, symbol text, qty real, price real)''')
Georg Brandl116aa622007-08-15 14:28:22 +000041
42 # Insert a row of data
Zachary Ware9d085622014-04-01 12:21:56 -050043 c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
Georg Brandl116aa622007-08-15 14:28:22 +000044
45 # Save (commit) the changes
46 conn.commit()
47
Zachary Ware9d085622014-04-01 12:21:56 -050048 # We can also close the connection if we are done with it.
49 # Just be sure any changes have been committed or they will be lost.
50 conn.close()
51
52The data you've saved is persistent and is available in subsequent sessions::
53
54 import sqlite3
55 conn = sqlite3.connect('example.db')
56 c = conn.cursor()
Georg Brandl116aa622007-08-15 14:28:22 +000057
58Usually your SQL operations will need to use values from Python variables. You
59shouldn't assemble your query using Python's string operations because doing so
Zachary Ware9d085622014-04-01 12:21:56 -050060is insecure; it makes your program vulnerable to an SQL injection attack
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030061(see https://xkcd.com/327/ for humorous example of what can go wrong).
Georg Brandl116aa622007-08-15 14:28:22 +000062
63Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
64wherever you want to use a value, and then provide a tuple of values as the
Georg Brandl8a1e4c42009-05-25 21:13:36 +000065second argument to the cursor's :meth:`~Cursor.execute` method. (Other database
66modules may use a different placeholder, such as ``%s`` or ``:1``.) For
67example::
Georg Brandl116aa622007-08-15 14:28:22 +000068
69 # Never do this -- insecure!
Zachary Ware9d085622014-04-01 12:21:56 -050070 symbol = 'RHAT'
71 c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
Georg Brandl116aa622007-08-15 14:28:22 +000072
73 # Do this instead
Zachary Ware9d085622014-04-01 12:21:56 -050074 t = ('RHAT',)
75 c.execute('SELECT * FROM stocks WHERE symbol=?', t)
76 print(c.fetchone())
Georg Brandl116aa622007-08-15 14:28:22 +000077
Zachary Ware9d085622014-04-01 12:21:56 -050078 # Larger example that inserts many records at a time
79 purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
80 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
81 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
82 ]
83 c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
Georg Brandl116aa622007-08-15 14:28:22 +000084
Georg Brandl9afde1c2007-11-01 20:32:30 +000085To retrieve data after executing a SELECT statement, you can either treat the
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000086cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
87retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandl9afde1c2007-11-01 20:32:30 +000088matching rows.
Georg Brandl116aa622007-08-15 14:28:22 +000089
90This example uses the iterator form::
91
Zachary Ware9d085622014-04-01 12:21:56 -050092 >>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
93 print(row)
94
Ezio Melottib5845052009-09-13 05:49:25 +000095 ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
96 ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
97 ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
Zachary Ware9d085622014-04-01 12:21:56 -050098 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
Georg Brandl116aa622007-08-15 14:28:22 +000099
100
101.. seealso::
102
Benjamin Peterson216e47d2014-01-16 09:52:38 -0500103 https://github.com/ghaering/pysqlite
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000104 The pysqlite web page -- sqlite3 is developed externally under the name
105 "pysqlite".
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300107 https://www.sqlite.org
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000108 The SQLite web page; the documentation describes the syntax and the
109 available data types for the supported SQL dialect.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Sanyam Khurana1b4587a2017-12-06 22:09:33 +0530111 https://www.w3schools.com/sql/
Zachary Ware9d085622014-04-01 12:21:56 -0500112 Tutorial, reference and examples for learning SQL syntax.
113
Georg Brandl116aa622007-08-15 14:28:22 +0000114 :pep:`249` - Database API Specification 2.0
115 PEP written by Marc-André Lemburg.
116
117
118.. _sqlite3-module-contents:
119
120Module functions and constants
121------------------------------
122
123
R David Murray3f7beb92013-01-10 20:18:21 -0500124.. data:: version
125
126 The version number of this module, as a string. This is not the version of
127 the SQLite library.
128
129
130.. data:: version_info
131
132 The version number of this module, as a tuple of integers. This is not the
133 version of the SQLite library.
134
135
136.. data:: sqlite_version
137
138 The version number of the run-time SQLite library, as a string.
139
140
141.. data:: sqlite_version_info
142
143 The version number of the run-time SQLite library, as a tuple of integers.
144
145
Georg Brandl116aa622007-08-15 14:28:22 +0000146.. data:: PARSE_DECLTYPES
147
148 This constant is meant to be used with the *detect_types* parameter of the
149 :func:`connect` function.
150
151 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000152 column it returns. It will parse out the first word of the declared type,
153 i. e. for "integer primary key", it will parse out "integer", or for
154 "number(10)" it will parse out "number". Then for that column, it will look
155 into the converters dictionary and use the converter function registered for
156 that type there.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158
159.. data:: PARSE_COLNAMES
160
161 This constant is meant to be used with the *detect_types* parameter of the
162 :func:`connect` function.
163
164 Setting this makes the SQLite interface parse the column name for each column it
165 returns. It will look for a string formed [mytype] in there, and then decide
166 that 'mytype' is the type of the column. It will try to find an entry of
167 'mytype' in the converters dictionary and then use the converter function found
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000168 there to return the value. The column name found in :attr:`Cursor.description`
Serhiy Storchakab1465682020-03-21 15:53:28 +0200169 does not include the type, i. e. if you use something like
170 ``'as "Expiration date [datetime]"'`` in your SQL, then we will parse out
171 everything until the first ``'['`` for the column name and strip
172 the preceeding space: the column name would simply be "Expiration date".
Georg Brandl116aa622007-08-15 14:28:22 +0000173
174
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100175.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])
Georg Brandl116aa622007-08-15 14:28:22 +0000176
Anders Lorentsena22a1272017-11-07 01:47:43 +0100177 Opens a connection to the SQLite database file *database*. By default returns a
178 :class:`Connection` object, unless a custom *factory* is given.
179
180 *database* is a :term:`path-like object` giving the pathname (absolute or
181 relative to the current working directory) of the database file to be opened.
182 You can use ``":memory:"`` to open a database connection to a database that
183 resides in RAM instead of on disk.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185 When a database is accessed by multiple connections, and one of the processes
186 modifies the database, the SQLite database is locked until that transaction is
187 committed. The *timeout* parameter specifies how long the connection should wait
188 for the lock to go away until raising an exception. The default for the timeout
189 parameter is 5.0 (five seconds).
190
191 For the *isolation_level* parameter, please see the
Berker Peksaga1bc2462016-09-07 04:02:41 +0300192 :attr:`~Connection.isolation_level` property of :class:`Connection` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Georg Brandl3c127112013-10-06 12:38:44 +0200194 SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
Georg Brandl116aa622007-08-15 14:28:22 +0000195 you want to use other types you must add support for them yourself. The
196 *detect_types* parameter and the using custom **converters** registered with the
197 module-level :func:`register_converter` function allow you to easily do that.
198
199 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
200 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
201 type detection on.
202
Senthil Kumaran7ee91942016-06-03 00:03:48 -0700203 By default, *check_same_thread* is :const:`True` and only the creating thread may
204 use the connection. If set :const:`False`, the returned connection may be shared
205 across multiple threads. When using multiple threads with the same connection
206 writing operations should be serialized by the user to avoid data corruption.
207
Georg Brandl116aa622007-08-15 14:28:22 +0000208 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
209 connect call. You can, however, subclass the :class:`Connection` class and make
210 :func:`connect` use your class instead by providing your class for the *factory*
211 parameter.
212
213 Consult the section :ref:`sqlite3-types` of this manual for details.
214
215 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
216 overhead. If you want to explicitly set the number of statements that are cached
217 for the connection, you can set the *cached_statements* parameter. The currently
218 implemented default is to cache 100 statements.
219
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100220 If *uri* is true, *database* is interpreted as a URI. This allows you
221 to specify options. For example, to open a database in read-only mode
222 you can use::
223
224 db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)
225
226 More information about this feature, including a list of recognized options, can
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300227 be found in the `SQLite URI documentation <https://www.sqlite.org/uri.html>`_.
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100228
Steve Dower44f91c32019-06-27 10:47:59 -0700229 .. audit-event:: sqlite3.connect database sqlite3.connect
Steve Dower60419a72019-06-24 08:42:54 -0700230
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100231 .. versionchanged:: 3.4
232 Added the *uri* parameter.
233
Anders Lorentsena22a1272017-11-07 01:47:43 +0100234 .. versionchanged:: 3.7
235 *database* can now also be a :term:`path-like object`, not only a string.
236
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238.. function:: register_converter(typename, callable)
239
240 Registers a callable to convert a bytestring from the database into a custom
241 Python type. The callable will be invoked for all database values that are of
242 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
Sergey Fedoseev831c2972018-07-03 16:59:32 +0500243 function for how the type detection works. Note that *typename* and the name of
244 the type in your query are matched in case-insensitive manner.
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246
247.. function:: register_adapter(type, callable)
248
249 Registers a callable to convert the custom Python type *type* into one of
250 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000251 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000252 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000253
254
255.. function:: complete_statement(sql)
256
257 Returns :const:`True` if the string *sql* contains one or more complete SQL
258 statements terminated by semicolons. It does not verify that the SQL is
259 syntactically correct, only that there are no unclosed string literals and the
260 statement is terminated by a semicolon.
261
262 This can be used to build a shell for SQLite, as in the following example:
263
264
265 .. literalinclude:: ../includes/sqlite3/complete_statement.py
266
267
268.. function:: enable_callback_tracebacks(flag)
269
270 By default you will not get any tracebacks in user-defined functions,
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200271 aggregates, converters, authorizer callbacks etc. If you want to debug them,
272 you can call this function with *flag* set to ``True``. Afterwards, you will
273 get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to
274 disable the feature again.
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276
277.. _sqlite3-connection-objects:
278
279Connection Objects
280------------------
281
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000282.. class:: Connection
283
284 A SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000285
R David Murray6db23352012-09-30 20:44:43 -0400286 .. attribute:: isolation_level
Georg Brandl116aa622007-08-15 14:28:22 +0000287
Berker Peksaga71fed02018-07-29 12:01:38 +0300288 Get or set the current default isolation level. :const:`None` for autocommit mode or
R David Murray6db23352012-09-30 20:44:43 -0400289 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
290 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000291
R David Murray6db23352012-09-30 20:44:43 -0400292 .. attribute:: in_transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000293
R David Murray6db23352012-09-30 20:44:43 -0400294 :const:`True` if a transaction is active (there are uncommitted changes),
295 :const:`False` otherwise. Read-only attribute.
R. David Murrayd35251d2010-06-01 01:32:12 +0000296
R David Murray6db23352012-09-30 20:44:43 -0400297 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000298
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300299 .. method:: cursor(factory=Cursor)
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300301 The cursor method accepts a single optional parameter *factory*. If
302 supplied, this must be a callable returning an instance of :class:`Cursor`
303 or its subclasses.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
R David Murray6db23352012-09-30 20:44:43 -0400305 .. method:: commit()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000306
R David Murray6db23352012-09-30 20:44:43 -0400307 This method commits the current transaction. If you don't call this method,
308 anything you did since the last call to ``commit()`` is not visible from
309 other database connections. If you wonder why you don't see the data you've
310 written to the database, please check you didn't forget to call this method.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000311
R David Murray6db23352012-09-30 20:44:43 -0400312 .. method:: rollback()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000313
R David Murray6db23352012-09-30 20:44:43 -0400314 This method rolls back any changes to the database since the last call to
315 :meth:`commit`.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000316
R David Murray6db23352012-09-30 20:44:43 -0400317 .. method:: close()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000318
R David Murray6db23352012-09-30 20:44:43 -0400319 This closes the database connection. Note that this does not automatically
320 call :meth:`commit`. If you just close your database connection without
321 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000322
Berker Peksagc4154402016-06-12 13:41:47 +0300323 .. method:: execute(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000324
Berker Peksagc4154402016-06-12 13:41:47 +0300325 This is a nonstandard shortcut that creates a cursor object by calling
326 the :meth:`~Connection.cursor` method, calls the cursor's
327 :meth:`~Cursor.execute` method with the *parameters* given, and returns
328 the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000329
Berker Peksagc4154402016-06-12 13:41:47 +0300330 .. method:: executemany(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000331
Berker Peksagc4154402016-06-12 13:41:47 +0300332 This is a nonstandard shortcut that creates a cursor object by
333 calling the :meth:`~Connection.cursor` method, calls the cursor's
334 :meth:`~Cursor.executemany` method with the *parameters* given, and
335 returns the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000336
R David Murray6db23352012-09-30 20:44:43 -0400337 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Berker Peksagc4154402016-06-12 13:41:47 +0300339 This is a nonstandard shortcut that creates a cursor object by
340 calling the :meth:`~Connection.cursor` method, calls the cursor's
341 :meth:`~Cursor.executescript` method with the given *sql_script*, and
342 returns the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Sergey Fedoseev08308582018-07-08 12:09:20 +0500344 .. method:: create_function(name, num_params, func, *, deterministic=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000345
R David Murray6db23352012-09-30 20:44:43 -0400346 Creates a user-defined function that you can later use from within SQL
347 statements under the function name *name*. *num_params* is the number of
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300348 parameters the function accepts (if *num_params* is -1, the function may
349 take any number of arguments), and *func* is a Python callable that is
Sergey Fedoseev08308582018-07-08 12:09:20 +0500350 called as the SQL function. If *deterministic* is true, the created function
351 is marked as `deterministic <https://sqlite.org/deterministic.html>`_, which
352 allows SQLite to perform additional optimizations. This flag is supported by
Marcin Niemirabc9aa812018-07-08 14:02:58 +0200353 SQLite 3.8.3 or higher, :exc:`NotSupportedError` will be raised if used
Sergey Fedoseev08308582018-07-08 12:09:20 +0500354 with older versions.
Georg Brandl116aa622007-08-15 14:28:22 +0000355
R David Murray6db23352012-09-30 20:44:43 -0400356 The function can return any of the types supported by SQLite: bytes, str, int,
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300357 float and ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
Sergey Fedoseev08308582018-07-08 12:09:20 +0500359 .. versionchanged:: 3.8
360 The *deterministic* parameter was added.
361
R David Murray6db23352012-09-30 20:44:43 -0400362 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000363
R David Murray6db23352012-09-30 20:44:43 -0400364 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl116aa622007-08-15 14:28:22 +0000365
366
R David Murray6db23352012-09-30 20:44:43 -0400367 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl116aa622007-08-15 14:28:22 +0000368
R David Murray6db23352012-09-30 20:44:43 -0400369 Creates a user-defined aggregate function.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
R David Murray6db23352012-09-30 20:44:43 -0400371 The aggregate class must implement a ``step`` method, which accepts the number
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300372 of parameters *num_params* (if *num_params* is -1, the function may take
373 any number of arguments), and a ``finalize`` method which will return the
R David Murray6db23352012-09-30 20:44:43 -0400374 final result of the aggregate.
Georg Brandl116aa622007-08-15 14:28:22 +0000375
R David Murray6db23352012-09-30 20:44:43 -0400376 The ``finalize`` method can return any of the types supported by SQLite:
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300377 bytes, str, int, float and ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000378
R David Murray6db23352012-09-30 20:44:43 -0400379 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000380
R David Murray6db23352012-09-30 20:44:43 -0400381 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383
R David Murray6db23352012-09-30 20:44:43 -0400384 .. method:: create_collation(name, callable)
Georg Brandl116aa622007-08-15 14:28:22 +0000385
R David Murray6db23352012-09-30 20:44:43 -0400386 Creates a collation with the specified *name* and *callable*. The callable will
387 be passed two string arguments. It should return -1 if the first is ordered
388 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
389 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
390 your comparisons don't affect other SQL operations.
Georg Brandl116aa622007-08-15 14:28:22 +0000391
R David Murray6db23352012-09-30 20:44:43 -0400392 Note that the callable will get its parameters as Python bytestrings, which will
393 normally be encoded in UTF-8.
Georg Brandl116aa622007-08-15 14:28:22 +0000394
R David Murray6db23352012-09-30 20:44:43 -0400395 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl116aa622007-08-15 14:28:22 +0000396
R David Murray6db23352012-09-30 20:44:43 -0400397 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl116aa622007-08-15 14:28:22 +0000398
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300399 To remove a collation, call ``create_collation`` with ``None`` as callable::
Georg Brandl116aa622007-08-15 14:28:22 +0000400
R David Murray6db23352012-09-30 20:44:43 -0400401 con.create_collation("reverse", None)
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403
R David Murray6db23352012-09-30 20:44:43 -0400404 .. method:: interrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000405
R David Murray6db23352012-09-30 20:44:43 -0400406 You can call this method from a different thread to abort any queries that might
407 be executing on the connection. The query will then abort and the caller will
408 get an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410
R David Murray6db23352012-09-30 20:44:43 -0400411 .. method:: set_authorizer(authorizer_callback)
Georg Brandl116aa622007-08-15 14:28:22 +0000412
R David Murray6db23352012-09-30 20:44:43 -0400413 This routine registers a callback. The callback is invoked for each attempt to
414 access a column of a table in the database. The callback should return
415 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
416 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
417 column should be treated as a NULL value. These constants are available in the
418 :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
R David Murray6db23352012-09-30 20:44:43 -0400420 The first argument to the callback signifies what kind of operation is to be
421 authorized. The second and third argument will be arguments or :const:`None`
422 depending on the first argument. The 4th argument is the name of the database
423 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
424 inner-most trigger or view that is responsible for the access attempt or
425 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl116aa622007-08-15 14:28:22 +0000426
R David Murray6db23352012-09-30 20:44:43 -0400427 Please consult the SQLite documentation about the possible values for the first
428 argument and the meaning of the second and third argument depending on the first
429 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Georg Brandl116aa622007-08-15 14:28:22 +0000431
R David Murray6db23352012-09-30 20:44:43 -0400432 .. method:: set_progress_handler(handler, n)
Georg Brandl116aa622007-08-15 14:28:22 +0000433
R David Murray6db23352012-09-30 20:44:43 -0400434 This routine registers a callback. The callback is invoked for every *n*
435 instructions of the SQLite virtual machine. This is useful if you want to
436 get called from SQLite during long-running operations, for example to update
437 a GUI.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000438
R David Murray6db23352012-09-30 20:44:43 -0400439 If you want to clear any previously installed progress handler, call the
440 method with :const:`None` for *handler*.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000441
Simon Willisonac03c032017-11-02 07:34:12 -0700442 Returning a non-zero value from the handler function will terminate the
443 currently executing query and cause it to raise an :exc:`OperationalError`
444 exception.
445
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000446
R David Murray842ca5f2012-09-30 20:49:19 -0400447 .. method:: set_trace_callback(trace_callback)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000448
R David Murray842ca5f2012-09-30 20:49:19 -0400449 Registers *trace_callback* to be called for each SQL statement that is
450 actually executed by the SQLite backend.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200451
R David Murray842ca5f2012-09-30 20:49:19 -0400452 The only argument passed to the callback is the statement (as string) that
453 is being executed. The return value of the callback is ignored. Note that
454 the backend does not only run statements passed to the :meth:`Cursor.execute`
455 methods. Other sources include the transaction management of the Python
456 module and the execution of triggers defined in the current database.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200457
R David Murray842ca5f2012-09-30 20:49:19 -0400458 Passing :const:`None` as *trace_callback* will disable the trace callback.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200459
R David Murray842ca5f2012-09-30 20:49:19 -0400460 .. versionadded:: 3.3
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200461
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200462
R David Murray6db23352012-09-30 20:44:43 -0400463 .. method:: enable_load_extension(enabled)
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200464
R David Murray6db23352012-09-30 20:44:43 -0400465 This routine allows/disallows the SQLite engine to load SQLite extensions
466 from shared libraries. SQLite extensions can define new functions,
467 aggregates or whole new virtual table implementations. One well-known
468 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000469
R David Murray6db23352012-09-30 20:44:43 -0400470 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000471
R David Murray6db23352012-09-30 20:44:43 -0400472 .. versionadded:: 3.2
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200473
R David Murray6db23352012-09-30 20:44:43 -0400474 .. literalinclude:: ../includes/sqlite3/load_extension.py
Georg Brandl67b21b72010-08-17 15:07:14 +0000475
R David Murray6db23352012-09-30 20:44:43 -0400476 .. method:: load_extension(path)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000477
R David Murray6db23352012-09-30 20:44:43 -0400478 This routine loads a SQLite extension from a shared library. You have to
479 enable extension loading with :meth:`enable_load_extension` before you can
480 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000481
R David Murray6db23352012-09-30 20:44:43 -0400482 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000483
R David Murray6db23352012-09-30 20:44:43 -0400484 .. versionadded:: 3.2
Gerhard Häringe0941c52010-10-03 21:47:06 +0000485
R David Murray6db23352012-09-30 20:44:43 -0400486 .. attribute:: row_factory
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200487
R David Murray6db23352012-09-30 20:44:43 -0400488 You can change this attribute to a callable that accepts the cursor and the
489 original row as a tuple and will return the real result row. This way, you can
490 implement more advanced ways of returning results, such as returning an object
491 that can also access columns by name.
Georg Brandl116aa622007-08-15 14:28:22 +0000492
R David Murray6db23352012-09-30 20:44:43 -0400493 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000494
R David Murray6db23352012-09-30 20:44:43 -0400495 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000496
R David Murray6db23352012-09-30 20:44:43 -0400497 If returning a tuple doesn't suffice and you want name-based access to
498 columns, you should consider setting :attr:`row_factory` to the
499 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
500 index-based and case-insensitive name-based access to columns with almost no
501 memory overhead. It will probably be better than your own custom
502 dictionary-based approach or even a db_row based solution.
Georg Brandl116aa622007-08-15 14:28:22 +0000503
R David Murray6db23352012-09-30 20:44:43 -0400504 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000505
Georg Brandl116aa622007-08-15 14:28:22 +0000506
R David Murray6db23352012-09-30 20:44:43 -0400507 .. attribute:: text_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000508
R David Murray6db23352012-09-30 20:44:43 -0400509 Using this attribute you can control what objects are returned for the ``TEXT``
510 data type. By default, this attribute is set to :class:`str` and the
511 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
512 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000513
R David Murray6db23352012-09-30 20:44:43 -0400514 You can also set it to any other callable that accepts a single bytestring
515 parameter and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000516
R David Murray6db23352012-09-30 20:44:43 -0400517 See the following example code for illustration:
Georg Brandl116aa622007-08-15 14:28:22 +0000518
R David Murray6db23352012-09-30 20:44:43 -0400519 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521
R David Murray6db23352012-09-30 20:44:43 -0400522 .. attribute:: total_changes
Georg Brandl116aa622007-08-15 14:28:22 +0000523
R David Murray6db23352012-09-30 20:44:43 -0400524 Returns the total number of database rows that have been modified, inserted, or
525 deleted since the database connection was opened.
Georg Brandl116aa622007-08-15 14:28:22 +0000526
527
Berker Peksag557a0632016-03-27 18:46:18 +0300528 .. method:: iterdump
Christian Heimesbbe741d2008-03-28 10:53:29 +0000529
R David Murray6db23352012-09-30 20:44:43 -0400530 Returns an iterator to dump the database in an SQL text format. Useful when
531 saving an in-memory database for later restoration. This function provides
532 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
533 shell.
Christian Heimesbbe741d2008-03-28 10:53:29 +0000534
R David Murray6db23352012-09-30 20:44:43 -0400535 Example::
Christian Heimesbbe741d2008-03-28 10:53:29 +0000536
R David Murray6db23352012-09-30 20:44:43 -0400537 # Convert file existing_db.db to SQL dump file dump.sql
Berker Peksag557a0632016-03-27 18:46:18 +0300538 import sqlite3
Christian Heimesbbe741d2008-03-28 10:53:29 +0000539
R David Murray6db23352012-09-30 20:44:43 -0400540 con = sqlite3.connect('existing_db.db')
541 with open('dump.sql', 'w') as f:
542 for line in con.iterdump():
543 f.write('%s\n' % line)
Xtreak287b84d2019-05-20 03:22:20 +0530544 con.close()
Christian Heimesbbe741d2008-03-28 10:53:29 +0000545
546
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100547 .. method:: backup(target, *, pages=0, progress=None, name="main", sleep=0.250)
548
549 This method makes a backup of a SQLite database even while it's being accessed
550 by other clients, or concurrently by the same connection. The copy will be
551 written into the mandatory argument *target*, that must be another
552 :class:`Connection` instance.
553
554 By default, or when *pages* is either ``0`` or a negative integer, the entire
555 database is copied in a single step; otherwise the method performs a loop
556 copying up to *pages* pages at a time.
557
558 If *progress* is specified, it must either be ``None`` or a callable object that
559 will be executed at each iteration with three integer arguments, respectively
560 the *status* of the last iteration, the *remaining* number of pages still to be
561 copied and the *total* number of pages.
562
563 The *name* argument specifies the database name that will be copied: it must be
564 a string containing either ``"main"``, the default, to indicate the main
565 database, ``"temp"`` to indicate the temporary database or the name specified
566 after the ``AS`` keyword in an ``ATTACH DATABASE`` statement for an attached
567 database.
568
569 The *sleep* argument specifies the number of seconds to sleep by between
570 successive attempts to backup remaining pages, can be specified either as an
571 integer or a floating point value.
572
573 Example 1, copy an existing database into another::
574
575 import sqlite3
576
577 def progress(status, remaining, total):
578 print(f'Copied {total-remaining} of {total} pages...')
579
580 con = sqlite3.connect('existing_db.db')
Xtreak287b84d2019-05-20 03:22:20 +0530581 bck = sqlite3.connect('backup.db')
582 with bck:
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100583 con.backup(bck, pages=1, progress=progress)
Xtreak287b84d2019-05-20 03:22:20 +0530584 bck.close()
585 con.close()
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100586
587 Example 2, copy an existing database into a transient copy::
588
589 import sqlite3
590
591 source = sqlite3.connect('existing_db.db')
592 dest = sqlite3.connect(':memory:')
593 source.backup(dest)
594
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100595 .. versionadded:: 3.7
596
597
Georg Brandl116aa622007-08-15 14:28:22 +0000598.. _sqlite3-cursor-objects:
599
600Cursor Objects
601--------------
602
Georg Brandl96115fb22010-10-17 09:33:24 +0000603.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000604
Georg Brandl96115fb22010-10-17 09:33:24 +0000605 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000606
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200607 .. index:: single: ? (question mark); in SQL statements
608 .. index:: single: : (colon); in SQL statements
609
Berker Peksagc4154402016-06-12 13:41:47 +0300610 .. method:: execute(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000611
Zachary Ware9d085622014-04-01 12:21:56 -0500612 Executes an SQL statement. The SQL statement may be parameterized (i. e.
R David Murray6db23352012-09-30 20:44:43 -0400613 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
614 kinds of placeholders: question marks (qmark style) and named placeholders
615 (named style).
Georg Brandl116aa622007-08-15 14:28:22 +0000616
R David Murray6db23352012-09-30 20:44:43 -0400617 Here's an example of both styles:
Georg Brandl116aa622007-08-15 14:28:22 +0000618
R David Murray6db23352012-09-30 20:44:43 -0400619 .. literalinclude:: ../includes/sqlite3/execute_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000620
R David Murray6db23352012-09-30 20:44:43 -0400621 :meth:`execute` will only execute a single SQL statement. If you try to execute
Berker Peksag7d92f892016-08-25 00:50:24 +0300622 more than one statement with it, it will raise a :exc:`.Warning`. Use
R David Murray6db23352012-09-30 20:44:43 -0400623 :meth:`executescript` if you want to execute multiple SQL statements with one
624 call.
Georg Brandl116aa622007-08-15 14:28:22 +0000625
626
R David Murray6db23352012-09-30 20:44:43 -0400627 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl116aa622007-08-15 14:28:22 +0000628
R David Murray6db23352012-09-30 20:44:43 -0400629 Executes an SQL command against all parameter sequences or mappings found in
Berker Peksagc4154402016-06-12 13:41:47 +0300630 the sequence *seq_of_parameters*. The :mod:`sqlite3` module also allows
631 using an :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000632
R David Murray6db23352012-09-30 20:44:43 -0400633 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000634
R David Murray6db23352012-09-30 20:44:43 -0400635 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000636
R David Murray6db23352012-09-30 20:44:43 -0400637 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl116aa622007-08-15 14:28:22 +0000638
639
R David Murray6db23352012-09-30 20:44:43 -0400640 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000641
R David Murray6db23352012-09-30 20:44:43 -0400642 This is a nonstandard convenience method for executing multiple SQL statements
643 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
644 gets as a parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Berker Peksagc4154402016-06-12 13:41:47 +0300646 *sql_script* can be an instance of :class:`str`.
Georg Brandl116aa622007-08-15 14:28:22 +0000647
R David Murray6db23352012-09-30 20:44:43 -0400648 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000649
R David Murray6db23352012-09-30 20:44:43 -0400650 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl116aa622007-08-15 14:28:22 +0000651
652
R David Murray6db23352012-09-30 20:44:43 -0400653 .. method:: fetchone()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000654
R David Murray6db23352012-09-30 20:44:43 -0400655 Fetches the next row of a query result set, returning a single sequence,
656 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000657
658
R David Murray6db23352012-09-30 20:44:43 -0400659 .. method:: fetchmany(size=cursor.arraysize)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000660
R David Murray6db23352012-09-30 20:44:43 -0400661 Fetches the next set of rows of a query result, returning a list. An empty
662 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000663
R David Murray6db23352012-09-30 20:44:43 -0400664 The number of rows to fetch per call is specified by the *size* parameter.
665 If it is not given, the cursor's arraysize determines the number of rows
666 to be fetched. The method should try to fetch as many rows as indicated by
667 the size parameter. If this is not possible due to the specified number of
668 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000669
R David Murray6db23352012-09-30 20:44:43 -0400670 Note there are performance considerations involved with the *size* parameter.
671 For optimal performance, it is usually best to use the arraysize attribute.
672 If the *size* parameter is used, then it is best for it to retain the same
673 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000674
R David Murray6db23352012-09-30 20:44:43 -0400675 .. method:: fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000676
R David Murray6db23352012-09-30 20:44:43 -0400677 Fetches all (remaining) rows of a query result, returning a list. Note that
678 the cursor's arraysize attribute can affect the performance of this operation.
679 An empty list is returned when no rows are available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000680
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300681 .. method:: close()
682
683 Close the cursor now (rather than whenever ``__del__`` is called).
684
Berker Peksaged789f92016-08-25 00:45:07 +0300685 The cursor will be unusable from this point forward; a :exc:`ProgrammingError`
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300686 exception will be raised if any operation is attempted with the cursor.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000687
R David Murray6db23352012-09-30 20:44:43 -0400688 .. attribute:: rowcount
Georg Brandl116aa622007-08-15 14:28:22 +0000689
R David Murray6db23352012-09-30 20:44:43 -0400690 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
691 attribute, the database engine's own support for the determination of "rows
692 affected"/"rows selected" is quirky.
Georg Brandl116aa622007-08-15 14:28:22 +0000693
R David Murray6db23352012-09-30 20:44:43 -0400694 For :meth:`executemany` statements, the number of modifications are summed up
695 into :attr:`rowcount`.
Georg Brandl116aa622007-08-15 14:28:22 +0000696
R David Murray6db23352012-09-30 20:44:43 -0400697 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
698 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
699 last operation is not determinable by the interface". This includes ``SELECT``
700 statements because we cannot determine the number of rows a query produced
701 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000702
R David Murray6db23352012-09-30 20:44:43 -0400703 .. attribute:: lastrowid
Gerhard Häringd3372792008-03-29 19:13:55 +0000704
R David Murray6db23352012-09-30 20:44:43 -0400705 This read-only attribute provides the rowid of the last modified row. It is
Berker Peksage0b70cd2016-06-14 15:25:36 +0300706 only set if you issued an ``INSERT`` or a ``REPLACE`` statement using the
707 :meth:`execute` method. For operations other than ``INSERT`` or
708 ``REPLACE`` or when :meth:`executemany` is called, :attr:`lastrowid` is
709 set to :const:`None`.
710
711 If the ``INSERT`` or ``REPLACE`` statement failed to insert the previous
712 successful rowid is returned.
713
714 .. versionchanged:: 3.6
715 Added support for the ``REPLACE`` statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000716
csabella02e12132017-04-04 01:16:14 -0400717 .. attribute:: arraysize
718
719 Read/write attribute that controls the number of rows returned by :meth:`fetchmany`.
720 The default value is 1 which means a single row would be fetched per call.
721
R David Murray6db23352012-09-30 20:44:43 -0400722 .. attribute:: description
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000723
R David Murray6db23352012-09-30 20:44:43 -0400724 This read-only attribute provides the column names of the last query. To
725 remain compatible with the Python DB API, it returns a 7-tuple for each
726 column where the last six items of each tuple are :const:`None`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000727
R David Murray6db23352012-09-30 20:44:43 -0400728 It is set for ``SELECT`` statements without any matching rows as well.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000729
Ezio Melotti62564db2016-03-18 20:10:36 +0200730 .. attribute:: connection
731
732 This read-only attribute provides the SQLite database :class:`Connection`
733 used by the :class:`Cursor` object. A :class:`Cursor` object created by
734 calling :meth:`con.cursor() <Connection.cursor>` will have a
735 :attr:`connection` attribute that refers to *con*::
736
737 >>> con = sqlite3.connect(":memory:")
738 >>> cur = con.cursor()
739 >>> cur.connection == con
740 True
741
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000742.. _sqlite3-row-objects:
743
744Row Objects
745-----------
746
747.. class:: Row
748
749 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000750 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000751 It tries to mimic a tuple in most of its features.
752
753 It supports mapping access by column name and index, iteration,
754 representation, equality testing and :func:`len`.
755
756 If two :class:`Row` objects have exactly the same columns and their
757 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000758
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000759 .. method:: keys
760
R David Murray092135e2014-06-05 15:16:38 -0400761 This method returns a list of column names. Immediately after a query,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000762 it is the first member of each tuple in :attr:`Cursor.description`.
763
Serhiy Storchaka72e731c2015-03-31 13:33:11 +0300764 .. versionchanged:: 3.5
765 Added support of slicing.
766
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000767Let's assume we initialize a table as in the example given above::
768
Senthil Kumaran946eb862011-07-03 10:17:22 -0700769 conn = sqlite3.connect(":memory:")
770 c = conn.cursor()
771 c.execute('''create table stocks
772 (date text, trans text, symbol text,
773 qty real, price real)''')
774 c.execute("""insert into stocks
775 values ('2006-01-05','BUY','RHAT',100,35.14)""")
776 conn.commit()
777 c.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000778
779Now we plug :class:`Row` in::
780
Senthil Kumaran946eb862011-07-03 10:17:22 -0700781 >>> conn.row_factory = sqlite3.Row
782 >>> c = conn.cursor()
783 >>> c.execute('select * from stocks')
784 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
785 >>> r = c.fetchone()
786 >>> type(r)
787 <class 'sqlite3.Row'>
788 >>> tuple(r)
789 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
790 >>> len(r)
791 5
792 >>> r[2]
793 'RHAT'
794 >>> r.keys()
795 ['date', 'trans', 'symbol', 'qty', 'price']
796 >>> r['qty']
797 100.0
798 >>> for member in r:
799 ... print(member)
800 ...
801 2006-01-05
802 BUY
803 RHAT
804 100.0
805 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000806
807
Berker Peksaged789f92016-08-25 00:45:07 +0300808.. _sqlite3-exceptions:
809
810Exceptions
811----------
812
813.. exception:: Warning
814
815 A subclass of :exc:`Exception`.
816
817.. exception:: Error
818
819 The base class of the other exceptions in this module. It is a subclass
820 of :exc:`Exception`.
821
822.. exception:: DatabaseError
823
824 Exception raised for errors that are related to the database.
825
826.. exception:: IntegrityError
827
828 Exception raised when the relational integrity of the database is affected,
829 e.g. a foreign key check fails. It is a subclass of :exc:`DatabaseError`.
830
831.. exception:: ProgrammingError
832
833 Exception raised for programming errors, e.g. table not found or already
834 exists, syntax error in the SQL statement, wrong number of parameters
835 specified, etc. It is a subclass of :exc:`DatabaseError`.
836
Zackery Spytz71ede002018-06-13 03:09:31 -0600837.. exception:: OperationalError
838
839 Exception raised for errors that are related to the database's operation
840 and not necessarily under the control of the programmer, e.g. an unexpected
841 disconnect occurs, the data source name is not found, a transaction could
842 not be processed, etc. It is a subclass of :exc:`DatabaseError`.
843
Marcin Niemirabc9aa812018-07-08 14:02:58 +0200844.. exception:: NotSupportedError
845
846 Exception raised in case a method or database API was used which is not
847 supported by the database, e.g. calling the :meth:`~Connection.rollback`
848 method on a connection that does not support transaction or has
849 transactions turned off. It is a subclass of :exc:`DatabaseError`.
850
Berker Peksaged789f92016-08-25 00:45:07 +0300851
Georg Brandl116aa622007-08-15 14:28:22 +0000852.. _sqlite3-types:
853
854SQLite and Python types
855-----------------------
856
857
858Introduction
859^^^^^^^^^^^^
860
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000861SQLite natively supports the following types: ``NULL``, ``INTEGER``,
862``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000863
864The following Python types can thus be sent to SQLite without any problem:
865
Georg Brandlf6945182008-02-01 11:56:49 +0000866+-------------------------------+-------------+
867| Python type | SQLite type |
868+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000869| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000870+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000871| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000872+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000873| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000874+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000875| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000876+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000877| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000878+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000879
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000880
Georg Brandl116aa622007-08-15 14:28:22 +0000881This is how SQLite types are converted to Python types by default:
882
Zachary Ware9d085622014-04-01 12:21:56 -0500883+-------------+----------------------------------------------+
884| SQLite type | Python type |
885+=============+==============================================+
886| ``NULL`` | :const:`None` |
887+-------------+----------------------------------------------+
888| ``INTEGER`` | :class:`int` |
889+-------------+----------------------------------------------+
890| ``REAL`` | :class:`float` |
891+-------------+----------------------------------------------+
892| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
893| | :class:`str` by default |
894+-------------+----------------------------------------------+
895| ``BLOB`` | :class:`bytes` |
896+-------------+----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000897
898The type system of the :mod:`sqlite3` module is extensible in two ways: you can
899store additional Python types in a SQLite database via object adaptation, and
900you can let the :mod:`sqlite3` module convert SQLite types to different Python
901types via converters.
902
903
904Using adapters to store additional Python types in SQLite databases
905^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
906
907As described before, SQLite supports only a limited set of types natively. To
908use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000909sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000910str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000911
Georg Brandl116aa622007-08-15 14:28:22 +0000912There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
913type to one of the supported ones.
914
915
916Letting your object adapt itself
917""""""""""""""""""""""""""""""""
918
919This is a good approach if you write the class yourself. Let's suppose you have
920a class like this::
921
Éric Araujo28053fb2010-11-22 03:09:19 +0000922 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000923 def __init__(self, x, y):
924 self.x, self.y = x, y
925
926Now you want to store the point in a single SQLite column. First you'll have to
Naglis441416c2020-05-06 19:51:43 +0000927choose one of the supported types to be used for representing the point.
Georg Brandl116aa622007-08-15 14:28:22 +0000928Let's just use str and separate the coordinates using a semicolon. Then you need
929to give your class a method ``__conform__(self, protocol)`` which must return
930the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
931
932.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
933
934
935Registering an adapter callable
936"""""""""""""""""""""""""""""""
937
938The other possibility is to create a function that converts the type to the
939string representation and register the function with :meth:`register_adapter`.
940
Georg Brandl116aa622007-08-15 14:28:22 +0000941.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
942
943The :mod:`sqlite3` module has two default adapters for Python's built-in
944:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
945we want to store :class:`datetime.datetime` objects not in ISO representation,
946but as a Unix timestamp.
947
948.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
949
950
951Converting SQLite values to custom Python types
952^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
953
954Writing an adapter lets you send custom Python types to SQLite. But to make it
955really useful we need to make the Python to SQLite to Python roundtrip work.
956
957Enter converters.
958
959Let's go back to the :class:`Point` class. We stored the x and y coordinates
960separated via semicolons as strings in SQLite.
961
962First, we'll define a converter function that accepts the string as a parameter
963and constructs a :class:`Point` object from it.
964
965.. note::
966
Zachary Ware9d085622014-04-01 12:21:56 -0500967 Converter functions **always** get called with a :class:`bytes` object, no
968 matter under which data type you sent the value to SQLite.
Georg Brandl116aa622007-08-15 14:28:22 +0000969
Georg Brandl116aa622007-08-15 14:28:22 +0000970::
971
972 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200973 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +0000974 return Point(x, y)
975
976Now you need to make the :mod:`sqlite3` module know that what you select from
977the database is actually a point. There are two ways of doing this:
978
979* Implicitly via the declared type
980
981* Explicitly via the column name
982
983Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
984for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
985
986The following example illustrates both approaches.
987
988.. literalinclude:: ../includes/sqlite3/converter_point.py
989
990
991Default adapters and converters
992^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
993
994There are default adapters for the date and datetime types in the datetime
995module. They will be sent as ISO dates/ISO timestamps to SQLite.
996
997The default converters are registered under the name "date" for
998:class:`datetime.date` and under the name "timestamp" for
999:class:`datetime.datetime`.
1000
1001This way, you can use date/timestamps from Python without any additional
1002fiddling in most cases. The format of the adapters is also compatible with the
1003experimental SQLite date/time functions.
1004
1005The following example demonstrates this.
1006
1007.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
1008
Petri Lehtinen5f794092013-02-26 21:32:02 +02001009If a timestamp stored in SQLite has a fractional part longer than 6
1010numbers, its value will be truncated to microsecond precision by the
1011timestamp converter.
1012
Georg Brandl116aa622007-08-15 14:28:22 +00001013
1014.. _sqlite3-controlling-transactions:
1015
1016Controlling Transactions
1017------------------------
1018
Berker Peksaga71fed02018-07-29 12:01:38 +03001019The underlying ``sqlite3`` library operates in ``autocommit`` mode by default,
1020but the Python :mod:`sqlite3` module by default does not.
1021
1022``autocommit`` mode means that statements that modify the database take effect
1023immediately. A ``BEGIN`` or ``SAVEPOINT`` statement disables ``autocommit``
1024mode, and a ``COMMIT``, a ``ROLLBACK``, or a ``RELEASE`` that ends the
1025outermost transaction, turns ``autocommit`` mode back on.
1026
1027The Python :mod:`sqlite3` module by default issues a ``BEGIN`` statement
1028implicitly before a Data Modification Language (DML) statement (i.e.
Berker Peksagab994ed2016-09-11 12:57:15 +03001029``INSERT``/``UPDATE``/``DELETE``/``REPLACE``).
Georg Brandl116aa622007-08-15 14:28:22 +00001030
Berker Peksaga71fed02018-07-29 12:01:38 +03001031You can control which kind of ``BEGIN`` statements :mod:`sqlite3` implicitly
1032executes via the *isolation_level* parameter to the :func:`connect`
Georg Brandl116aa622007-08-15 14:28:22 +00001033call, or via the :attr:`isolation_level` property of connections.
Berker Peksaga71fed02018-07-29 12:01:38 +03001034If you specify no *isolation_level*, a plain ``BEGIN`` is used, which is
1035equivalent to specifying ``DEFERRED``. Other possible values are ``IMMEDIATE``
1036and ``EXCLUSIVE``.
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Berker Peksaga71fed02018-07-29 12:01:38 +03001038You can disable the :mod:`sqlite3` module's implicit transaction management by
1039setting :attr:`isolation_level` to ``None``. This will leave the underlying
1040``sqlite3`` library operating in ``autocommit`` mode. You can then completely
1041control the transaction state by explicitly issuing ``BEGIN``, ``ROLLBACK``,
1042``SAVEPOINT``, and ``RELEASE`` statements in your code.
Berker Peksagfe70d922017-02-26 18:31:12 +03001043
Berker Peksagab994ed2016-09-11 12:57:15 +03001044.. versionchanged:: 3.6
1045 :mod:`sqlite3` used to implicitly commit an open transaction before DDL
1046 statements. This is no longer the case.
Georg Brandl116aa622007-08-15 14:28:22 +00001047
1048
Georg Brandl8a1e4c42009-05-25 21:13:36 +00001049Using :mod:`sqlite3` efficiently
1050--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001051
1052
1053Using shortcut methods
1054^^^^^^^^^^^^^^^^^^^^^^
1055
1056Using the nonstandard :meth:`execute`, :meth:`executemany` and
1057:meth:`executescript` methods of the :class:`Connection` object, your code can
1058be written more concisely because you don't have to create the (often
1059superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
1060objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001061objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +00001062directly using only a single call on the :class:`Connection` object.
1063
1064.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
1065
1066
1067Accessing columns by name instead of by index
1068^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1069
Georg Brandl22b34312009-07-26 14:54:51 +00001070One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +00001071:class:`sqlite3.Row` class designed to be used as a row factory.
1072
1073Rows wrapped with this class can be accessed both by index (like tuples) and
1074case-insensitively by name:
1075
1076.. literalinclude:: ../includes/sqlite3/rowclass.py
1077
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +00001078
1079Using the connection as a context manager
1080^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1081
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +00001082Connection objects can be used as context managers
1083that automatically commit or rollback transactions. In the event of an
1084exception, the transaction is rolled back; otherwise, the transaction is
1085committed:
1086
1087.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +00001088
1089
1090Common issues
1091-------------
1092
1093Multithreading
1094^^^^^^^^^^^^^^
1095
1096Older SQLite versions had issues with sharing connections between threads.
1097That's why the Python module disallows sharing connections and cursors between
1098threads. If you still try to do so, you will get an exception at runtime.
1099
1100The only exception is calling the :meth:`~Connection.interrupt` method, which
1101only makes sense to call from a different thread.
1102
Gerhard Häringe0941c52010-10-03 21:47:06 +00001103.. rubric:: Footnotes
1104
1105.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumaran946eb862011-07-03 10:17:22 -07001106 default, because some platforms (notably Mac OS X) have SQLite
1107 libraries which are compiled without this feature. To get loadable
1108 extension support, you must pass --enable-loadable-sqlite-extensions to
1109 configure.