blob: e7c191b9f61e9467cde6a1d883c6029b2b95cbbb [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
Jelle Zijlstrad8ba5c12022-03-11 17:10:55 -080020The sqlite3 module was written by Gerhard Häring. It provides an SQL interface
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +020021compliant with the DB-API 2.0 specification described by :pep:`249`, and
Erlend Egeberg Aaslandcf0b2392021-01-06 01:02:43 +010022requires SQLite 3.7.15 or newer.
Georg Brandl116aa622007-08-15 14:28:22 +000023
Miss Islington (bot)94dad5e2021-11-15 15:31:38 -080024To use the module, start by creating a :class:`Connection` object that
Georg Brandl116aa622007-08-15 14:28:22 +000025represents 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
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010029 con = sqlite3.connect('example.db')
Georg Brandl116aa622007-08-15 14:28:22 +000030
Miss Islington (bot)94dad5e2021-11-15 15:31:38 -080031The special path name ``:memory:`` can be provided to create a temporary
32database in RAM.
Georg Brandl116aa622007-08-15 14:28:22 +000033
Miss Islington (bot)94dad5e2021-11-15 15:31:38 -080034Once a :class:`Connection` has been established, create a :class:`Cursor` object
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000035and call its :meth:`~Cursor.execute` method to perform SQL commands::
Georg Brandl116aa622007-08-15 14:28:22 +000036
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010037 cur = con.cursor()
Georg Brandl116aa622007-08-15 14:28:22 +000038
39 # Create table
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010040 cur.execute('''CREATE TABLE stocks
41 (date text, trans text, symbol text, qty real, price real)''')
Georg Brandl116aa622007-08-15 14:28:22 +000042
43 # Insert a row of data
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010044 cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
Georg Brandl116aa622007-08-15 14:28:22 +000045
46 # Save (commit) the changes
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010047 con.commit()
Georg Brandl116aa622007-08-15 14:28:22 +000048
Zachary Ware9d085622014-04-01 12:21:56 -050049 # We can also close the connection if we are done with it.
50 # Just be sure any changes have been committed or they will be lost.
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010051 con.close()
Zachary Ware9d085622014-04-01 12:21:56 -050052
Miss Islington (bot)94dad5e2021-11-15 15:31:38 -080053The saved data is persistent: it can be reloaded in a subsequent session even
54after restarting the Python interpreter::
Zachary Ware9d085622014-04-01 12:21:56 -050055
56 import sqlite3
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010057 con = sqlite3.connect('example.db')
58 cur = con.cursor()
Georg Brandl116aa622007-08-15 14:28:22 +000059
Miss Islington (bot)94dad5e2021-11-15 15:31:38 -080060To retrieve data after executing a SELECT statement, either treat the cursor as
61an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
62retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list
63of the matching rows.
Georg Brandl116aa622007-08-15 14:28:22 +000064
65This example uses the iterator form::
66
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010067 >>> for row in cur.execute('SELECT * FROM stocks ORDER BY price'):
Zachary Ware9d085622014-04-01 12:21:56 -050068 print(row)
69
Ezio Melottib5845052009-09-13 05:49:25 +000070 ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
71 ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
72 ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
Zachary Ware9d085622014-04-01 12:21:56 -050073 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
Georg Brandl116aa622007-08-15 14:28:22 +000074
75
Erlend Egeberg Aasland3386ca02021-04-14 14:28:55 +020076.. _sqlite3-placeholders:
77
Miss Islington (bot)94dad5e2021-11-15 15:31:38 -080078SQL operations usually need to use values from Python variables. However,
79beware of using Python's string operations to assemble queries, as they
80are vulnerable to SQL injection attacks (see the `xkcd webcomic
81<https://xkcd.com/327/>`_ for a humorous example of what can go wrong)::
Erlend Egeberg Aasland3386ca02021-04-14 14:28:55 +020082
83 # Never do this -- insecure!
84 symbol = 'RHAT'
85 cur.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
86
Miss Islington (bot)94dad5e2021-11-15 15:31:38 -080087Instead, use the DB-API's parameter substitution. To insert a variable into a
88query string, use a placeholder in the string, and substitute the actual values
89into the query by providing them as a :class:`tuple` of values to the second
90argument of the cursor's :meth:`~Cursor.execute` method. An SQL statement may
Erlend Egeberg Aasland3386ca02021-04-14 14:28:55 +020091use one of two kinds of placeholders: question marks (qmark style) or named
92placeholders (named style). For the qmark style, ``parameters`` must be a
93:term:`sequence <sequence>`. For the named style, it can be either a
94:term:`sequence <sequence>` or :class:`dict` instance. The length of the
95:term:`sequence <sequence>` must match the number of placeholders, or a
96:exc:`ProgrammingError` is raised. If a :class:`dict` is given, it must contain
Miss Islington (bot)94dad5e2021-11-15 15:31:38 -080097keys for all named parameters. Any extra items are ignored. Here's an example of
98both styles:
Erlend Egeberg Aasland3386ca02021-04-14 14:28:55 +020099
100.. literalinclude:: ../includes/sqlite3/execute_1.py
101
102
Georg Brandl116aa622007-08-15 14:28:22 +0000103.. seealso::
104
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300105 https://www.sqlite.org
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000106 The SQLite web page; the documentation describes the syntax and the
107 available data types for the supported SQL dialect.
Georg Brandl116aa622007-08-15 14:28:22 +0000108
Sanyam Khurana1b4587a2017-12-06 22:09:33 +0530109 https://www.w3schools.com/sql/
Zachary Ware9d085622014-04-01 12:21:56 -0500110 Tutorial, reference and examples for learning SQL syntax.
111
Georg Brandl116aa622007-08-15 14:28:22 +0000112 :pep:`249` - Database API Specification 2.0
113 PEP written by Marc-André Lemburg.
114
115
116.. _sqlite3-module-contents:
117
118Module functions and constants
119------------------------------
120
121
Miss Islington (bot)1d88b2b2021-10-28 12:57:14 -0700122.. data:: apilevel
123
124 String constant stating the supported DB-API level. Required by the DB-API.
125 Hard-coded to ``"2.0"``.
126
127.. data:: paramstyle
128
129 String constant stating the type of parameter marker formatting expected by
130 the :mod:`sqlite3` module. Required by the DB-API. Hard-coded to
131 ``"qmark"``.
132
133 .. note::
134
135 The :mod:`sqlite3` module supports both ``qmark`` and ``numeric`` DB-API
136 parameter styles, because that is what the underlying SQLite library
137 supports. However, the DB-API does not allow multiple values for
138 the ``paramstyle`` attribute.
139
R David Murray3f7beb92013-01-10 20:18:21 -0500140.. data:: version
141
142 The version number of this module, as a string. This is not the version of
143 the SQLite library.
144
145
146.. data:: version_info
147
148 The version number of this module, as a tuple of integers. This is not the
149 version of the SQLite library.
150
151
152.. data:: sqlite_version
153
154 The version number of the run-time SQLite library, as a string.
155
156
157.. data:: sqlite_version_info
158
159 The version number of the run-time SQLite library, as a tuple of integers.
160
161
Miss Islington (bot)1d88b2b2021-10-28 12:57:14 -0700162.. data:: threadsafety
163
164 Integer constant required by the DB-API, stating the level of thread safety
165 the :mod:`sqlite3` module supports. Currently hard-coded to ``1``, meaning
166 *"Threads may share the module, but not connections."* However, this may not
167 always be true. You can check the underlying SQLite library's compile-time
168 threaded mode using the following query::
169
170 import sqlite3
171 con = sqlite3.connect(":memory:")
172 con.execute("""
173 select * from pragma_compile_options
174 where compile_options like 'THREADSAFE=%'
175 """).fetchall()
176
177 Note that the `SQLITE_THREADSAFE levels
178 <https://sqlite.org/compile.html#threadsafe>`_ do not match the DB-API 2.0
179 ``threadsafety`` levels.
180
181
Georg Brandl116aa622007-08-15 14:28:22 +0000182.. data:: PARSE_DECLTYPES
183
184 This constant is meant to be used with the *detect_types* parameter of the
185 :func:`connect` function.
186
187 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000188 column it returns. It will parse out the first word of the declared type,
189 i. e. for "integer primary key", it will parse out "integer", or for
190 "number(10)" it will parse out "number". Then for that column, it will look
191 into the converters dictionary and use the converter function registered for
192 that type there.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
194
195.. data:: PARSE_COLNAMES
196
197 This constant is meant to be used with the *detect_types* parameter of the
198 :func:`connect` function.
199
200 Setting this makes the SQLite interface parse the column name for each column it
201 returns. It will look for a string formed [mytype] in there, and then decide
202 that 'mytype' is the type of the column. It will try to find an entry of
203 'mytype' in the converters dictionary and then use the converter function found
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000204 there to return the value. The column name found in :attr:`Cursor.description`
Serhiy Storchakab1465682020-03-21 15:53:28 +0200205 does not include the type, i. e. if you use something like
206 ``'as "Expiration date [datetime]"'`` in your SQL, then we will parse out
207 everything until the first ``'['`` for the column name and strip
Miss Islington (bot)a90a57e2021-07-28 07:33:26 -0700208 the preceding space: the column name would simply be "Expiration date".
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100211.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])
Georg Brandl116aa622007-08-15 14:28:22 +0000212
Anders Lorentsena22a1272017-11-07 01:47:43 +0100213 Opens a connection to the SQLite database file *database*. By default returns a
214 :class:`Connection` object, unless a custom *factory* is given.
215
216 *database* is a :term:`path-like object` giving the pathname (absolute or
217 relative to the current working directory) of the database file to be opened.
218 You can use ``":memory:"`` to open a database connection to a database that
219 resides in RAM instead of on disk.
Georg Brandl116aa622007-08-15 14:28:22 +0000220
221 When a database is accessed by multiple connections, and one of the processes
222 modifies the database, the SQLite database is locked until that transaction is
223 committed. The *timeout* parameter specifies how long the connection should wait
224 for the lock to go away until raising an exception. The default for the timeout
225 parameter is 5.0 (five seconds).
226
227 For the *isolation_level* parameter, please see the
Berker Peksaga1bc2462016-09-07 04:02:41 +0300228 :attr:`~Connection.isolation_level` property of :class:`Connection` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000229
Georg Brandl3c127112013-10-06 12:38:44 +0200230 SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
Georg Brandl116aa622007-08-15 14:28:22 +0000231 you want to use other types you must add support for them yourself. The
232 *detect_types* parameter and the using custom **converters** registered with the
233 module-level :func:`register_converter` function allow you to easily do that.
234
235 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
236 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
sblondon09a36cd2020-12-19 23:52:39 +0100237 type detection on. Due to SQLite behaviour, types can't be detected for generated
238 fields (for example ``max(data)``), even when *detect_types* parameter is set. In
239 such case, the returned type is :class:`str`.
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Senthil Kumaran7ee91942016-06-03 00:03:48 -0700241 By default, *check_same_thread* is :const:`True` and only the creating thread may
242 use the connection. If set :const:`False`, the returned connection may be shared
243 across multiple threads. When using multiple threads with the same connection
244 writing operations should be serialized by the user to avoid data corruption.
245
Georg Brandl116aa622007-08-15 14:28:22 +0000246 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
247 connect call. You can, however, subclass the :class:`Connection` class and make
248 :func:`connect` use your class instead by providing your class for the *factory*
249 parameter.
250
251 Consult the section :ref:`sqlite3-types` of this manual for details.
252
253 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
254 overhead. If you want to explicitly set the number of statements that are cached
255 for the connection, you can set the *cached_statements* parameter. The currently
256 implemented default is to cache 100 statements.
257
Erlend Egeberg Aasland01e6cbe2022-01-18 22:57:33 +0100258 If *uri* is :const:`True`, *database* is interpreted as a
259 :abbr:`URI (Uniform Resource Identifier)` with a file path and an optional
260 query string. The scheme part *must* be ``"file:"``. The path can be a
261 relative or absolute file path. The query string allows us to pass
262 parameters to SQLite. Some useful URI tricks include::
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100263
Erlend Egeberg Aasland01e6cbe2022-01-18 22:57:33 +0100264 # Open a database in read-only mode.
265 con = sqlite3.connect("file:template.db?mode=ro", uri=True)
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100266
Erlend Egeberg Aasland01e6cbe2022-01-18 22:57:33 +0100267 # Don't implicitly create a new database file if it does not already exist.
268 # Will raise sqlite3.OperationalError if unable to open a database file.
269 con = sqlite3.connect("file:nosuchdb.db?mode=rw", uri=True)
270
271 # Create a shared named in-memory database.
272 con1 = sqlite3.connect("file:mem1?mode=memory&cache=shared", uri=True)
273 con2 = sqlite3.connect("file:mem1?mode=memory&cache=shared", uri=True)
274 con1.executescript("create table t(t); insert into t values(28);")
275 rows = con2.execute("select * from t").fetchall()
276
277 More information about this feature, including a list of recognized
278 parameters, can be found in the
279 `SQLite URI documentation <https://www.sqlite.org/uri.html>`_.
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100280
Steve Dower44f91c32019-06-27 10:47:59 -0700281 .. audit-event:: sqlite3.connect database sqlite3.connect
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200282 .. audit-event:: sqlite3.connect/handle connection_handle sqlite3.connect
Steve Dower60419a72019-06-24 08:42:54 -0700283
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100284 .. versionchanged:: 3.4
285 Added the *uri* parameter.
286
Anders Lorentsena22a1272017-11-07 01:47:43 +0100287 .. versionchanged:: 3.7
288 *database* can now also be a :term:`path-like object`, not only a string.
289
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200290 .. versionchanged:: 3.10
291 Added the ``sqlite3.connect/handle`` auditing event.
292
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294.. function:: register_converter(typename, callable)
295
296 Registers a callable to convert a bytestring from the database into a custom
297 Python type. The callable will be invoked for all database values that are of
298 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
Sergey Fedoseev831c2972018-07-03 16:59:32 +0500299 function for how the type detection works. Note that *typename* and the name of
300 the type in your query are matched in case-insensitive manner.
Georg Brandl116aa622007-08-15 14:28:22 +0000301
302
303.. function:: register_adapter(type, callable)
304
305 Registers a callable to convert the custom Python type *type* into one of
306 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000307 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000308 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310
311.. function:: complete_statement(sql)
312
313 Returns :const:`True` if the string *sql* contains one or more complete SQL
314 statements terminated by semicolons. It does not verify that the SQL is
315 syntactically correct, only that there are no unclosed string literals and the
316 statement is terminated by a semicolon.
317
318 This can be used to build a shell for SQLite, as in the following example:
319
320
321 .. literalinclude:: ../includes/sqlite3/complete_statement.py
322
323
324.. function:: enable_callback_tracebacks(flag)
325
326 By default you will not get any tracebacks in user-defined functions,
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200327 aggregates, converters, authorizer callbacks etc. If you want to debug them,
328 you can call this function with *flag* set to ``True``. Afterwards, you will
329 get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to
330 disable the feature again.
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332
333.. _sqlite3-connection-objects:
334
335Connection Objects
336------------------
337
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000338.. class:: Connection
339
Jelle Zijlstrad8ba5c12022-03-11 17:10:55 -0800340 An SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000341
R David Murray6db23352012-09-30 20:44:43 -0400342 .. attribute:: isolation_level
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Berker Peksaga71fed02018-07-29 12:01:38 +0300344 Get or set the current default isolation level. :const:`None` for autocommit mode or
R David Murray6db23352012-09-30 20:44:43 -0400345 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
346 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
R David Murray6db23352012-09-30 20:44:43 -0400348 .. attribute:: in_transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000349
R David Murray6db23352012-09-30 20:44:43 -0400350 :const:`True` if a transaction is active (there are uncommitted changes),
351 :const:`False` otherwise. Read-only attribute.
R. David Murrayd35251d2010-06-01 01:32:12 +0000352
R David Murray6db23352012-09-30 20:44:43 -0400353 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000354
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300355 .. method:: cursor(factory=Cursor)
Georg Brandl116aa622007-08-15 14:28:22 +0000356
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300357 The cursor method accepts a single optional parameter *factory*. If
358 supplied, this must be a callable returning an instance of :class:`Cursor`
359 or its subclasses.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
R David Murray6db23352012-09-30 20:44:43 -0400361 .. method:: commit()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000362
R David Murray6db23352012-09-30 20:44:43 -0400363 This method commits the current transaction. If you don't call this method,
364 anything you did since the last call to ``commit()`` is not visible from
365 other database connections. If you wonder why you don't see the data you've
366 written to the database, please check you didn't forget to call this method.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000367
R David Murray6db23352012-09-30 20:44:43 -0400368 .. method:: rollback()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000369
R David Murray6db23352012-09-30 20:44:43 -0400370 This method rolls back any changes to the database since the last call to
371 :meth:`commit`.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000372
R David Murray6db23352012-09-30 20:44:43 -0400373 .. method:: close()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000374
R David Murray6db23352012-09-30 20:44:43 -0400375 This closes the database connection. Note that this does not automatically
376 call :meth:`commit`. If you just close your database connection without
377 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000378
Berker Peksagc4154402016-06-12 13:41:47 +0300379 .. method:: execute(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Berker Peksagc4154402016-06-12 13:41:47 +0300381 This is a nonstandard shortcut that creates a cursor object by calling
382 the :meth:`~Connection.cursor` method, calls the cursor's
383 :meth:`~Cursor.execute` method with the *parameters* given, and returns
384 the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Berker Peksagc4154402016-06-12 13:41:47 +0300386 .. method:: executemany(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Berker Peksagc4154402016-06-12 13:41:47 +0300388 This is a nonstandard shortcut that creates a cursor object by
389 calling the :meth:`~Connection.cursor` method, calls the cursor's
390 :meth:`~Cursor.executemany` method with the *parameters* given, and
391 returns the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000392
R David Murray6db23352012-09-30 20:44:43 -0400393 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000394
Berker Peksagc4154402016-06-12 13:41:47 +0300395 This is a nonstandard shortcut that creates a cursor object by
396 calling the :meth:`~Connection.cursor` method, calls the cursor's
397 :meth:`~Cursor.executescript` method with the given *sql_script*, and
398 returns the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000399
Sergey Fedoseev08308582018-07-08 12:09:20 +0500400 .. method:: create_function(name, num_params, func, *, deterministic=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000401
R David Murray6db23352012-09-30 20:44:43 -0400402 Creates a user-defined function that you can later use from within SQL
403 statements under the function name *name*. *num_params* is the number of
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300404 parameters the function accepts (if *num_params* is -1, the function may
405 take any number of arguments), and *func* is a Python callable that is
Sergey Fedoseev08308582018-07-08 12:09:20 +0500406 called as the SQL function. If *deterministic* is true, the created function
407 is marked as `deterministic <https://sqlite.org/deterministic.html>`_, which
408 allows SQLite to perform additional optimizations. This flag is supported by
Marcin Niemirabc9aa812018-07-08 14:02:58 +0200409 SQLite 3.8.3 or higher, :exc:`NotSupportedError` will be raised if used
Sergey Fedoseev08308582018-07-08 12:09:20 +0500410 with older versions.
Georg Brandl116aa622007-08-15 14:28:22 +0000411
R David Murray6db23352012-09-30 20:44:43 -0400412 The function can return any of the types supported by SQLite: bytes, str, int,
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300413 float and ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Sergey Fedoseev08308582018-07-08 12:09:20 +0500415 .. versionchanged:: 3.8
416 The *deterministic* parameter was added.
417
R David Murray6db23352012-09-30 20:44:43 -0400418 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000419
R David Murray6db23352012-09-30 20:44:43 -0400420 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl116aa622007-08-15 14:28:22 +0000421
422
R David Murray6db23352012-09-30 20:44:43 -0400423 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl116aa622007-08-15 14:28:22 +0000424
R David Murray6db23352012-09-30 20:44:43 -0400425 Creates a user-defined aggregate function.
Georg Brandl116aa622007-08-15 14:28:22 +0000426
R David Murray6db23352012-09-30 20:44:43 -0400427 The aggregate class must implement a ``step`` method, which accepts the number
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300428 of parameters *num_params* (if *num_params* is -1, the function may take
429 any number of arguments), and a ``finalize`` method which will return the
R David Murray6db23352012-09-30 20:44:43 -0400430 final result of the aggregate.
Georg Brandl116aa622007-08-15 14:28:22 +0000431
R David Murray6db23352012-09-30 20:44:43 -0400432 The ``finalize`` method can return any of the types supported by SQLite:
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300433 bytes, str, int, float and ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000434
R David Murray6db23352012-09-30 20:44:43 -0400435 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000436
R David Murray6db23352012-09-30 20:44:43 -0400437 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439
R David Murray6db23352012-09-30 20:44:43 -0400440 .. method:: create_collation(name, callable)
Georg Brandl116aa622007-08-15 14:28:22 +0000441
R David Murray6db23352012-09-30 20:44:43 -0400442 Creates a collation with the specified *name* and *callable*. The callable will
443 be passed two string arguments. It should return -1 if the first is ordered
444 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
445 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
446 your comparisons don't affect other SQL operations.
Georg Brandl116aa622007-08-15 14:28:22 +0000447
R David Murray6db23352012-09-30 20:44:43 -0400448 Note that the callable will get its parameters as Python bytestrings, which will
449 normally be encoded in UTF-8.
Georg Brandl116aa622007-08-15 14:28:22 +0000450
R David Murray6db23352012-09-30 20:44:43 -0400451 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl116aa622007-08-15 14:28:22 +0000452
R David Murray6db23352012-09-30 20:44:43 -0400453 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl116aa622007-08-15 14:28:22 +0000454
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300455 To remove a collation, call ``create_collation`` with ``None`` as callable::
Georg Brandl116aa622007-08-15 14:28:22 +0000456
R David Murray6db23352012-09-30 20:44:43 -0400457 con.create_collation("reverse", None)
Georg Brandl116aa622007-08-15 14:28:22 +0000458
459
R David Murray6db23352012-09-30 20:44:43 -0400460 .. method:: interrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000461
R David Murray6db23352012-09-30 20:44:43 -0400462 You can call this method from a different thread to abort any queries that might
463 be executing on the connection. The query will then abort and the caller will
464 get an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
466
R David Murray6db23352012-09-30 20:44:43 -0400467 .. method:: set_authorizer(authorizer_callback)
Georg Brandl116aa622007-08-15 14:28:22 +0000468
R David Murray6db23352012-09-30 20:44:43 -0400469 This routine registers a callback. The callback is invoked for each attempt to
470 access a column of a table in the database. The callback should return
471 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
472 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
473 column should be treated as a NULL value. These constants are available in the
474 :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000475
R David Murray6db23352012-09-30 20:44:43 -0400476 The first argument to the callback signifies what kind of operation is to be
477 authorized. The second and third argument will be arguments or :const:`None`
478 depending on the first argument. The 4th argument is the name of the database
479 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
480 inner-most trigger or view that is responsible for the access attempt or
481 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl116aa622007-08-15 14:28:22 +0000482
R David Murray6db23352012-09-30 20:44:43 -0400483 Please consult the SQLite documentation about the possible values for the first
484 argument and the meaning of the second and third argument depending on the first
485 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000486
Georg Brandl116aa622007-08-15 14:28:22 +0000487
R David Murray6db23352012-09-30 20:44:43 -0400488 .. method:: set_progress_handler(handler, n)
Georg Brandl116aa622007-08-15 14:28:22 +0000489
R David Murray6db23352012-09-30 20:44:43 -0400490 This routine registers a callback. The callback is invoked for every *n*
491 instructions of the SQLite virtual machine. This is useful if you want to
492 get called from SQLite during long-running operations, for example to update
493 a GUI.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000494
R David Murray6db23352012-09-30 20:44:43 -0400495 If you want to clear any previously installed progress handler, call the
496 method with :const:`None` for *handler*.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000497
Simon Willisonac03c032017-11-02 07:34:12 -0700498 Returning a non-zero value from the handler function will terminate the
499 currently executing query and cause it to raise an :exc:`OperationalError`
500 exception.
501
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000502
R David Murray842ca5f2012-09-30 20:49:19 -0400503 .. method:: set_trace_callback(trace_callback)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000504
R David Murray842ca5f2012-09-30 20:49:19 -0400505 Registers *trace_callback* to be called for each SQL statement that is
506 actually executed by the SQLite backend.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200507
Miss Islington (bot)87f0ac82021-09-15 12:00:02 -0700508 The only argument passed to the callback is the statement (as
509 :class:`str`) that is being executed. The return value of the callback is
510 ignored. Note that the backend does not only run statements passed to the
511 :meth:`Cursor.execute` methods. Other sources include the
512 :ref:`transaction management <sqlite3-controlling-transactions>` of the
513 sqlite3 module and the execution of triggers defined in the current
514 database.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200515
R David Murray842ca5f2012-09-30 20:49:19 -0400516 Passing :const:`None` as *trace_callback* will disable the trace callback.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200517
Miss Islington (bot)87f0ac82021-09-15 12:00:02 -0700518 .. note::
519 Exceptions raised in the trace callback are not propagated. As a
520 development and debugging aid, use
521 :meth:`~sqlite3.enable_callback_tracebacks` to enable printing
522 tracebacks from exceptions raised in the trace callback.
523
R David Murray842ca5f2012-09-30 20:49:19 -0400524 .. versionadded:: 3.3
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200525
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200526
R David Murray6db23352012-09-30 20:44:43 -0400527 .. method:: enable_load_extension(enabled)
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200528
R David Murray6db23352012-09-30 20:44:43 -0400529 This routine allows/disallows the SQLite engine to load SQLite extensions
530 from shared libraries. SQLite extensions can define new functions,
531 aggregates or whole new virtual table implementations. One well-known
532 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000533
R David Murray6db23352012-09-30 20:44:43 -0400534 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000535
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200536 .. audit-event:: sqlite3.enable_load_extension connection,enabled sqlite3.enable_load_extension
537
R David Murray6db23352012-09-30 20:44:43 -0400538 .. versionadded:: 3.2
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200539
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200540 .. versionchanged:: 3.10
541 Added the ``sqlite3.enable_load_extension`` auditing event.
542
R David Murray6db23352012-09-30 20:44:43 -0400543 .. literalinclude:: ../includes/sqlite3/load_extension.py
Georg Brandl67b21b72010-08-17 15:07:14 +0000544
R David Murray6db23352012-09-30 20:44:43 -0400545 .. method:: load_extension(path)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000546
Jelle Zijlstrad8ba5c12022-03-11 17:10:55 -0800547 This routine loads an SQLite extension from a shared library. You have to
R David Murray6db23352012-09-30 20:44:43 -0400548 enable extension loading with :meth:`enable_load_extension` before you can
549 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000550
R David Murray6db23352012-09-30 20:44:43 -0400551 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000552
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200553 .. audit-event:: sqlite3.load_extension connection,path sqlite3.load_extension
554
R David Murray6db23352012-09-30 20:44:43 -0400555 .. versionadded:: 3.2
Gerhard Häringe0941c52010-10-03 21:47:06 +0000556
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200557 .. versionchanged:: 3.10
558 Added the ``sqlite3.load_extension`` auditing event.
559
R David Murray6db23352012-09-30 20:44:43 -0400560 .. attribute:: row_factory
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200561
R David Murray6db23352012-09-30 20:44:43 -0400562 You can change this attribute to a callable that accepts the cursor and the
563 original row as a tuple and will return the real result row. This way, you can
564 implement more advanced ways of returning results, such as returning an object
565 that can also access columns by name.
Georg Brandl116aa622007-08-15 14:28:22 +0000566
R David Murray6db23352012-09-30 20:44:43 -0400567 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000568
R David Murray6db23352012-09-30 20:44:43 -0400569 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000570
R David Murray6db23352012-09-30 20:44:43 -0400571 If returning a tuple doesn't suffice and you want name-based access to
572 columns, you should consider setting :attr:`row_factory` to the
573 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
574 index-based and case-insensitive name-based access to columns with almost no
575 memory overhead. It will probably be better than your own custom
576 dictionary-based approach or even a db_row based solution.
Georg Brandl116aa622007-08-15 14:28:22 +0000577
R David Murray6db23352012-09-30 20:44:43 -0400578 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000579
Georg Brandl116aa622007-08-15 14:28:22 +0000580
R David Murray6db23352012-09-30 20:44:43 -0400581 .. attribute:: text_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000582
R David Murray6db23352012-09-30 20:44:43 -0400583 Using this attribute you can control what objects are returned for the ``TEXT``
584 data type. By default, this attribute is set to :class:`str` and the
Miss Islington (bot)258c5fb2021-10-05 14:04:27 -0700585 :mod:`sqlite3` module will return :class:`str` objects for ``TEXT``.
586 If you want to return :class:`bytes` instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000587
R David Murray6db23352012-09-30 20:44:43 -0400588 You can also set it to any other callable that accepts a single bytestring
589 parameter and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000590
R David Murray6db23352012-09-30 20:44:43 -0400591 See the following example code for illustration:
Georg Brandl116aa622007-08-15 14:28:22 +0000592
R David Murray6db23352012-09-30 20:44:43 -0400593 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000594
595
R David Murray6db23352012-09-30 20:44:43 -0400596 .. attribute:: total_changes
Georg Brandl116aa622007-08-15 14:28:22 +0000597
R David Murray6db23352012-09-30 20:44:43 -0400598 Returns the total number of database rows that have been modified, inserted, or
599 deleted since the database connection was opened.
Georg Brandl116aa622007-08-15 14:28:22 +0000600
601
Berker Peksag557a0632016-03-27 18:46:18 +0300602 .. method:: iterdump
Christian Heimesbbe741d2008-03-28 10:53:29 +0000603
R David Murray6db23352012-09-30 20:44:43 -0400604 Returns an iterator to dump the database in an SQL text format. Useful when
605 saving an in-memory database for later restoration. This function provides
606 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
607 shell.
Christian Heimesbbe741d2008-03-28 10:53:29 +0000608
R David Murray6db23352012-09-30 20:44:43 -0400609 Example::
Christian Heimesbbe741d2008-03-28 10:53:29 +0000610
R David Murray6db23352012-09-30 20:44:43 -0400611 # Convert file existing_db.db to SQL dump file dump.sql
Berker Peksag557a0632016-03-27 18:46:18 +0300612 import sqlite3
Christian Heimesbbe741d2008-03-28 10:53:29 +0000613
R David Murray6db23352012-09-30 20:44:43 -0400614 con = sqlite3.connect('existing_db.db')
615 with open('dump.sql', 'w') as f:
616 for line in con.iterdump():
617 f.write('%s\n' % line)
Xtreak287b84d2019-05-20 03:22:20 +0530618 con.close()
Christian Heimesbbe741d2008-03-28 10:53:29 +0000619
620
Erlend Egeberg Aaslandabba83b2020-12-27 23:35:17 +0100621 .. method:: backup(target, *, pages=-1, progress=None, name="main", sleep=0.250)
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100622
Jelle Zijlstrad8ba5c12022-03-11 17:10:55 -0800623 This method makes a backup of an SQLite database even while it's being accessed
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100624 by other clients, or concurrently by the same connection. The copy will be
625 written into the mandatory argument *target*, that must be another
626 :class:`Connection` instance.
627
628 By default, or when *pages* is either ``0`` or a negative integer, the entire
629 database is copied in a single step; otherwise the method performs a loop
630 copying up to *pages* pages at a time.
631
632 If *progress* is specified, it must either be ``None`` or a callable object that
633 will be executed at each iteration with three integer arguments, respectively
634 the *status* of the last iteration, the *remaining* number of pages still to be
635 copied and the *total* number of pages.
636
637 The *name* argument specifies the database name that will be copied: it must be
638 a string containing either ``"main"``, the default, to indicate the main
639 database, ``"temp"`` to indicate the temporary database or the name specified
640 after the ``AS`` keyword in an ``ATTACH DATABASE`` statement for an attached
641 database.
642
643 The *sleep* argument specifies the number of seconds to sleep by between
644 successive attempts to backup remaining pages, can be specified either as an
645 integer or a floating point value.
646
647 Example 1, copy an existing database into another::
648
649 import sqlite3
650
651 def progress(status, remaining, total):
652 print(f'Copied {total-remaining} of {total} pages...')
653
654 con = sqlite3.connect('existing_db.db')
Xtreak287b84d2019-05-20 03:22:20 +0530655 bck = sqlite3.connect('backup.db')
656 with bck:
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100657 con.backup(bck, pages=1, progress=progress)
Xtreak287b84d2019-05-20 03:22:20 +0530658 bck.close()
659 con.close()
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100660
661 Example 2, copy an existing database into a transient copy::
662
663 import sqlite3
664
665 source = sqlite3.connect('existing_db.db')
666 dest = sqlite3.connect(':memory:')
667 source.backup(dest)
668
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100669 .. versionadded:: 3.7
670
671
Georg Brandl116aa622007-08-15 14:28:22 +0000672.. _sqlite3-cursor-objects:
673
674Cursor Objects
675--------------
676
Georg Brandl96115fb22010-10-17 09:33:24 +0000677.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000678
Georg Brandl96115fb22010-10-17 09:33:24 +0000679 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000680
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200681 .. index:: single: ? (question mark); in SQL statements
682 .. index:: single: : (colon); in SQL statements
683
Berker Peksagc4154402016-06-12 13:41:47 +0300684 .. method:: execute(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Erlend Egeberg Aasland3386ca02021-04-14 14:28:55 +0200686 Executes an SQL statement. Values may be bound to the statement using
687 :ref:`placeholders <sqlite3-placeholders>`.
Georg Brandl116aa622007-08-15 14:28:22 +0000688
R David Murray6db23352012-09-30 20:44:43 -0400689 :meth:`execute` will only execute a single SQL statement. If you try to execute
Berker Peksag7d92f892016-08-25 00:50:24 +0300690 more than one statement with it, it will raise a :exc:`.Warning`. Use
R David Murray6db23352012-09-30 20:44:43 -0400691 :meth:`executescript` if you want to execute multiple SQL statements with one
692 call.
Georg Brandl116aa622007-08-15 14:28:22 +0000693
694
R David Murray6db23352012-09-30 20:44:43 -0400695 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl116aa622007-08-15 14:28:22 +0000696
Erlend Egeberg Aasland3386ca02021-04-14 14:28:55 +0200697 Executes a :ref:`parameterized <sqlite3-placeholders>` SQL command
698 against all parameter sequences or mappings found in the sequence
699 *seq_of_parameters*. The :mod:`sqlite3` module also allows using an
700 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
R David Murray6db23352012-09-30 20:44:43 -0400702 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000703
R David Murray6db23352012-09-30 20:44:43 -0400704 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000705
R David Murray6db23352012-09-30 20:44:43 -0400706 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl116aa622007-08-15 14:28:22 +0000707
708
R David Murray6db23352012-09-30 20:44:43 -0400709 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000710
R David Murray6db23352012-09-30 20:44:43 -0400711 This is a nonstandard convenience method for executing multiple SQL statements
712 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
Miss Islington (bot)1f483c02021-05-19 00:37:33 -0700713 gets as a parameter. This method disregards :attr:`isolation_level`; any
Miss Islington (bot)3048b8b2021-07-14 15:22:50 -0700714 transaction control must be added to *sql_script*.
Georg Brandl116aa622007-08-15 14:28:22 +0000715
Berker Peksagc4154402016-06-12 13:41:47 +0300716 *sql_script* can be an instance of :class:`str`.
Georg Brandl116aa622007-08-15 14:28:22 +0000717
R David Murray6db23352012-09-30 20:44:43 -0400718 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000719
R David Murray6db23352012-09-30 20:44:43 -0400720 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl116aa622007-08-15 14:28:22 +0000721
722
R David Murray6db23352012-09-30 20:44:43 -0400723 .. method:: fetchone()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000724
R David Murray6db23352012-09-30 20:44:43 -0400725 Fetches the next row of a query result set, returning a single sequence,
726 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000727
728
R David Murray6db23352012-09-30 20:44:43 -0400729 .. method:: fetchmany(size=cursor.arraysize)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000730
R David Murray6db23352012-09-30 20:44:43 -0400731 Fetches the next set of rows of a query result, returning a list. An empty
732 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000733
R David Murray6db23352012-09-30 20:44:43 -0400734 The number of rows to fetch per call is specified by the *size* parameter.
735 If it is not given, the cursor's arraysize determines the number of rows
736 to be fetched. The method should try to fetch as many rows as indicated by
737 the size parameter. If this is not possible due to the specified number of
738 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000739
R David Murray6db23352012-09-30 20:44:43 -0400740 Note there are performance considerations involved with the *size* parameter.
741 For optimal performance, it is usually best to use the arraysize attribute.
742 If the *size* parameter is used, then it is best for it to retain the same
743 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000744
R David Murray6db23352012-09-30 20:44:43 -0400745 .. method:: fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000746
R David Murray6db23352012-09-30 20:44:43 -0400747 Fetches all (remaining) rows of a query result, returning a list. Note that
748 the cursor's arraysize attribute can affect the performance of this operation.
749 An empty list is returned when no rows are available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000750
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300751 .. method:: close()
752
753 Close the cursor now (rather than whenever ``__del__`` is called).
754
Berker Peksaged789f92016-08-25 00:45:07 +0300755 The cursor will be unusable from this point forward; a :exc:`ProgrammingError`
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300756 exception will be raised if any operation is attempted with the cursor.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000757
Miss Islington (bot)1d88b2b2021-10-28 12:57:14 -0700758 .. method:: setinputsizes(sizes)
759
Jelle Zijlstra5dfe9812022-03-09 10:19:27 -0800760 Required by the DB-API. Does nothing in :mod:`sqlite3`.
Miss Islington (bot)1d88b2b2021-10-28 12:57:14 -0700761
762 .. method:: setoutputsize(size [, column])
763
Jelle Zijlstra5dfe9812022-03-09 10:19:27 -0800764 Required by the DB-API. Does nothing in :mod:`sqlite3`.
Miss Islington (bot)1d88b2b2021-10-28 12:57:14 -0700765
R David Murray6db23352012-09-30 20:44:43 -0400766 .. attribute:: rowcount
Georg Brandl116aa622007-08-15 14:28:22 +0000767
R David Murray6db23352012-09-30 20:44:43 -0400768 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
769 attribute, the database engine's own support for the determination of "rows
770 affected"/"rows selected" is quirky.
Georg Brandl116aa622007-08-15 14:28:22 +0000771
R David Murray6db23352012-09-30 20:44:43 -0400772 For :meth:`executemany` statements, the number of modifications are summed up
773 into :attr:`rowcount`.
Georg Brandl116aa622007-08-15 14:28:22 +0000774
R David Murray6db23352012-09-30 20:44:43 -0400775 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
776 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
777 last operation is not determinable by the interface". This includes ``SELECT``
778 statements because we cannot determine the number of rows a query produced
779 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000780
R David Murray6db23352012-09-30 20:44:43 -0400781 .. attribute:: lastrowid
Gerhard Häringd3372792008-03-29 19:13:55 +0000782
Miss Islington (bot)987fba12022-01-08 12:05:43 -0800783 This read-only attribute provides the row id of the last inserted row. It
784 is only updated after successful ``INSERT`` or ``REPLACE`` statements
785 using the :meth:`execute` method. For other statements, after
786 :meth:`executemany` or :meth:`executescript`, or if the insertion failed,
787 the value of ``lastrowid`` is left unchanged. The initial value of
788 ``lastrowid`` is :const:`None`.
Berker Peksage0b70cd2016-06-14 15:25:36 +0300789
Miss Islington (bot)987fba12022-01-08 12:05:43 -0800790 .. note::
791 Inserts into ``WITHOUT ROWID`` tables are not recorded.
Berker Peksage0b70cd2016-06-14 15:25:36 +0300792
793 .. versionchanged:: 3.6
794 Added support for the ``REPLACE`` statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000795
csabella02e12132017-04-04 01:16:14 -0400796 .. attribute:: arraysize
797
798 Read/write attribute that controls the number of rows returned by :meth:`fetchmany`.
799 The default value is 1 which means a single row would be fetched per call.
800
R David Murray6db23352012-09-30 20:44:43 -0400801 .. attribute:: description
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000802
R David Murray6db23352012-09-30 20:44:43 -0400803 This read-only attribute provides the column names of the last query. To
804 remain compatible with the Python DB API, it returns a 7-tuple for each
805 column where the last six items of each tuple are :const:`None`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000806
R David Murray6db23352012-09-30 20:44:43 -0400807 It is set for ``SELECT`` statements without any matching rows as well.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000808
Ezio Melotti62564db2016-03-18 20:10:36 +0200809 .. attribute:: connection
810
811 This read-only attribute provides the SQLite database :class:`Connection`
812 used by the :class:`Cursor` object. A :class:`Cursor` object created by
813 calling :meth:`con.cursor() <Connection.cursor>` will have a
814 :attr:`connection` attribute that refers to *con*::
815
816 >>> con = sqlite3.connect(":memory:")
817 >>> cur = con.cursor()
818 >>> cur.connection == con
819 True
820
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000821.. _sqlite3-row-objects:
822
823Row Objects
824-----------
825
826.. class:: Row
827
828 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000829 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000830 It tries to mimic a tuple in most of its features.
831
832 It supports mapping access by column name and index, iteration,
833 representation, equality testing and :func:`len`.
834
835 If two :class:`Row` objects have exactly the same columns and their
836 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000837
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000838 .. method:: keys
839
R David Murray092135e2014-06-05 15:16:38 -0400840 This method returns a list of column names. Immediately after a query,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000841 it is the first member of each tuple in :attr:`Cursor.description`.
842
Serhiy Storchaka72e731c2015-03-31 13:33:11 +0300843 .. versionchanged:: 3.5
844 Added support of slicing.
845
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000846Let's assume we initialize a table as in the example given above::
847
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +0100848 con = sqlite3.connect(":memory:")
849 cur = con.cursor()
850 cur.execute('''create table stocks
Senthil Kumaran946eb862011-07-03 10:17:22 -0700851 (date text, trans text, symbol text,
852 qty real, price real)''')
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +0100853 cur.execute("""insert into stocks
854 values ('2006-01-05','BUY','RHAT',100,35.14)""")
855 con.commit()
856 cur.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000857
858Now we plug :class:`Row` in::
859
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +0100860 >>> con.row_factory = sqlite3.Row
861 >>> cur = con.cursor()
862 >>> cur.execute('select * from stocks')
Senthil Kumaran946eb862011-07-03 10:17:22 -0700863 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +0100864 >>> r = cur.fetchone()
Senthil Kumaran946eb862011-07-03 10:17:22 -0700865 >>> type(r)
866 <class 'sqlite3.Row'>
867 >>> tuple(r)
868 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
869 >>> len(r)
870 5
871 >>> r[2]
872 'RHAT'
873 >>> r.keys()
874 ['date', 'trans', 'symbol', 'qty', 'price']
875 >>> r['qty']
876 100.0
877 >>> for member in r:
878 ... print(member)
879 ...
880 2006-01-05
881 BUY
882 RHAT
883 100.0
884 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000885
886
Berker Peksaged789f92016-08-25 00:45:07 +0300887.. _sqlite3-exceptions:
888
889Exceptions
890----------
891
892.. exception:: Warning
893
894 A subclass of :exc:`Exception`.
895
896.. exception:: Error
897
898 The base class of the other exceptions in this module. It is a subclass
899 of :exc:`Exception`.
900
901.. exception:: DatabaseError
902
903 Exception raised for errors that are related to the database.
904
905.. exception:: IntegrityError
906
907 Exception raised when the relational integrity of the database is affected,
908 e.g. a foreign key check fails. It is a subclass of :exc:`DatabaseError`.
909
910.. exception:: ProgrammingError
911
912 Exception raised for programming errors, e.g. table not found or already
913 exists, syntax error in the SQL statement, wrong number of parameters
914 specified, etc. It is a subclass of :exc:`DatabaseError`.
915
Zackery Spytz71ede002018-06-13 03:09:31 -0600916.. exception:: OperationalError
917
918 Exception raised for errors that are related to the database's operation
919 and not necessarily under the control of the programmer, e.g. an unexpected
920 disconnect occurs, the data source name is not found, a transaction could
921 not be processed, etc. It is a subclass of :exc:`DatabaseError`.
922
Marcin Niemirabc9aa812018-07-08 14:02:58 +0200923.. exception:: NotSupportedError
924
925 Exception raised in case a method or database API was used which is not
926 supported by the database, e.g. calling the :meth:`~Connection.rollback`
927 method on a connection that does not support transaction or has
928 transactions turned off. It is a subclass of :exc:`DatabaseError`.
929
Berker Peksaged789f92016-08-25 00:45:07 +0300930
Georg Brandl116aa622007-08-15 14:28:22 +0000931.. _sqlite3-types:
932
933SQLite and Python types
934-----------------------
935
936
937Introduction
938^^^^^^^^^^^^
939
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000940SQLite natively supports the following types: ``NULL``, ``INTEGER``,
941``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000942
943The following Python types can thus be sent to SQLite without any problem:
944
Georg Brandlf6945182008-02-01 11:56:49 +0000945+-------------------------------+-------------+
946| Python type | SQLite type |
947+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000948| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000949+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000950| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000951+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000952| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000953+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000954| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000955+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000956| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000957+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000958
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000959
Georg Brandl116aa622007-08-15 14:28:22 +0000960This is how SQLite types are converted to Python types by default:
961
Zachary Ware9d085622014-04-01 12:21:56 -0500962+-------------+----------------------------------------------+
963| SQLite type | Python type |
964+=============+==============================================+
965| ``NULL`` | :const:`None` |
966+-------------+----------------------------------------------+
967| ``INTEGER`` | :class:`int` |
968+-------------+----------------------------------------------+
969| ``REAL`` | :class:`float` |
970+-------------+----------------------------------------------+
971| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
972| | :class:`str` by default |
973+-------------+----------------------------------------------+
974| ``BLOB`` | :class:`bytes` |
975+-------------+----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000976
977The type system of the :mod:`sqlite3` module is extensible in two ways: you can
Jelle Zijlstrad8ba5c12022-03-11 17:10:55 -0800978store additional Python types in an SQLite database via object adaptation, and
Georg Brandl116aa622007-08-15 14:28:22 +0000979you can let the :mod:`sqlite3` module convert SQLite types to different Python
980types via converters.
981
982
983Using adapters to store additional Python types in SQLite databases
984^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
985
986As described before, SQLite supports only a limited set of types natively. To
987use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000988sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000989str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000990
Georg Brandl116aa622007-08-15 14:28:22 +0000991There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
992type to one of the supported ones.
993
994
995Letting your object adapt itself
996""""""""""""""""""""""""""""""""
997
998This is a good approach if you write the class yourself. Let's suppose you have
999a class like this::
1000
Éric Araujo28053fb2010-11-22 03:09:19 +00001001 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +00001002 def __init__(self, x, y):
1003 self.x, self.y = x, y
1004
1005Now you want to store the point in a single SQLite column. First you'll have to
Naglis441416c2020-05-06 19:51:43 +00001006choose one of the supported types to be used for representing the point.
Georg Brandl116aa622007-08-15 14:28:22 +00001007Let's just use str and separate the coordinates using a semicolon. Then you need
1008to give your class a method ``__conform__(self, protocol)`` which must return
1009the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
1010
1011.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
1012
1013
1014Registering an adapter callable
1015"""""""""""""""""""""""""""""""
1016
1017The other possibility is to create a function that converts the type to the
1018string representation and register the function with :meth:`register_adapter`.
1019
Georg Brandl116aa622007-08-15 14:28:22 +00001020.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
1021
1022The :mod:`sqlite3` module has two default adapters for Python's built-in
1023:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
1024we want to store :class:`datetime.datetime` objects not in ISO representation,
1025but as a Unix timestamp.
1026
1027.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
1028
1029
1030Converting SQLite values to custom Python types
1031^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1032
1033Writing an adapter lets you send custom Python types to SQLite. But to make it
1034really useful we need to make the Python to SQLite to Python roundtrip work.
1035
1036Enter converters.
1037
1038Let's go back to the :class:`Point` class. We stored the x and y coordinates
1039separated via semicolons as strings in SQLite.
1040
1041First, we'll define a converter function that accepts the string as a parameter
1042and constructs a :class:`Point` object from it.
1043
1044.. note::
1045
Zachary Ware9d085622014-04-01 12:21:56 -05001046 Converter functions **always** get called with a :class:`bytes` object, no
1047 matter under which data type you sent the value to SQLite.
Georg Brandl116aa622007-08-15 14:28:22 +00001048
Georg Brandl116aa622007-08-15 14:28:22 +00001049::
1050
1051 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +02001052 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +00001053 return Point(x, y)
1054
1055Now you need to make the :mod:`sqlite3` module know that what you select from
1056the database is actually a point. There are two ways of doing this:
1057
1058* Implicitly via the declared type
1059
1060* Explicitly via the column name
1061
1062Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
1063for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
1064
1065The following example illustrates both approaches.
1066
1067.. literalinclude:: ../includes/sqlite3/converter_point.py
1068
1069
1070Default adapters and converters
1071^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1072
1073There are default adapters for the date and datetime types in the datetime
1074module. They will be sent as ISO dates/ISO timestamps to SQLite.
1075
1076The default converters are registered under the name "date" for
1077:class:`datetime.date` and under the name "timestamp" for
1078:class:`datetime.datetime`.
1079
1080This way, you can use date/timestamps from Python without any additional
1081fiddling in most cases. The format of the adapters is also compatible with the
1082experimental SQLite date/time functions.
1083
1084The following example demonstrates this.
1085
1086.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
1087
Petri Lehtinen5f794092013-02-26 21:32:02 +02001088If a timestamp stored in SQLite has a fractional part longer than 6
1089numbers, its value will be truncated to microsecond precision by the
1090timestamp converter.
1091
Miss Islington (bot)8ea665c2021-10-29 13:41:45 -07001092.. note::
1093
1094 The default "timestamp" converter ignores UTC offsets in the database and
1095 always returns a naive :class:`datetime.datetime` object. To preserve UTC
1096 offsets in timestamps, either leave converters disabled, or register an
1097 offset-aware converter with :func:`register_converter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001098
1099.. _sqlite3-controlling-transactions:
1100
1101Controlling Transactions
1102------------------------
1103
Berker Peksaga71fed02018-07-29 12:01:38 +03001104The underlying ``sqlite3`` library operates in ``autocommit`` mode by default,
1105but the Python :mod:`sqlite3` module by default does not.
1106
1107``autocommit`` mode means that statements that modify the database take effect
1108immediately. A ``BEGIN`` or ``SAVEPOINT`` statement disables ``autocommit``
1109mode, and a ``COMMIT``, a ``ROLLBACK``, or a ``RELEASE`` that ends the
1110outermost transaction, turns ``autocommit`` mode back on.
1111
1112The Python :mod:`sqlite3` module by default issues a ``BEGIN`` statement
1113implicitly before a Data Modification Language (DML) statement (i.e.
Berker Peksagab994ed2016-09-11 12:57:15 +03001114``INSERT``/``UPDATE``/``DELETE``/``REPLACE``).
Georg Brandl116aa622007-08-15 14:28:22 +00001115
Berker Peksaga71fed02018-07-29 12:01:38 +03001116You can control which kind of ``BEGIN`` statements :mod:`sqlite3` implicitly
1117executes via the *isolation_level* parameter to the :func:`connect`
Georg Brandl116aa622007-08-15 14:28:22 +00001118call, or via the :attr:`isolation_level` property of connections.
Berker Peksaga71fed02018-07-29 12:01:38 +03001119If you specify no *isolation_level*, a plain ``BEGIN`` is used, which is
1120equivalent to specifying ``DEFERRED``. Other possible values are ``IMMEDIATE``
1121and ``EXCLUSIVE``.
Georg Brandl116aa622007-08-15 14:28:22 +00001122
Berker Peksaga71fed02018-07-29 12:01:38 +03001123You can disable the :mod:`sqlite3` module's implicit transaction management by
1124setting :attr:`isolation_level` to ``None``. This will leave the underlying
1125``sqlite3`` library operating in ``autocommit`` mode. You can then completely
1126control the transaction state by explicitly issuing ``BEGIN``, ``ROLLBACK``,
1127``SAVEPOINT``, and ``RELEASE`` statements in your code.
Berker Peksagfe70d922017-02-26 18:31:12 +03001128
Miss Islington (bot)1f483c02021-05-19 00:37:33 -07001129Note that :meth:`~Cursor.executescript` disregards
1130:attr:`isolation_level`; any transaction control must be added explicitly.
1131
Berker Peksagab994ed2016-09-11 12:57:15 +03001132.. versionchanged:: 3.6
1133 :mod:`sqlite3` used to implicitly commit an open transaction before DDL
1134 statements. This is no longer the case.
Georg Brandl116aa622007-08-15 14:28:22 +00001135
1136
Georg Brandl8a1e4c42009-05-25 21:13:36 +00001137Using :mod:`sqlite3` efficiently
1138--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001139
1140
1141Using shortcut methods
1142^^^^^^^^^^^^^^^^^^^^^^
1143
1144Using the nonstandard :meth:`execute`, :meth:`executemany` and
1145:meth:`executescript` methods of the :class:`Connection` object, your code can
1146be written more concisely because you don't have to create the (often
1147superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
1148objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001149objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +00001150directly using only a single call on the :class:`Connection` object.
1151
1152.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
1153
1154
1155Accessing columns by name instead of by index
1156^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1157
Georg Brandl22b34312009-07-26 14:54:51 +00001158One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +00001159:class:`sqlite3.Row` class designed to be used as a row factory.
1160
1161Rows wrapped with this class can be accessed both by index (like tuples) and
1162case-insensitively by name:
1163
1164.. literalinclude:: ../includes/sqlite3/rowclass.py
1165
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +00001166
1167Using the connection as a context manager
1168^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1169
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +00001170Connection objects can be used as context managers
1171that automatically commit or rollback transactions. In the event of an
1172exception, the transaction is rolled back; otherwise, the transaction is
1173committed:
1174
1175.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +00001176
1177
Gerhard Häringe0941c52010-10-03 21:47:06 +00001178.. rubric:: Footnotes
1179
1180.. [#f1] The sqlite3 module is not built with loadable extension support by
Miss Islington (bot)1493e1a2021-09-23 03:25:31 -07001181 default, because some platforms (notably macOS) have SQLite
Senthil Kumaran946eb862011-07-03 10:17:22 -07001182 libraries which are compiled without this feature. To get loadable
Victor Stinner85918e42021-04-12 23:27:35 +02001183 extension support, you must pass the
1184 :option:`--enable-loadable-sqlite-extensions` option to configure.