blob: d0f28db12fda16e59a75deec1a5290dc48093e49 [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
Erlend Egeberg Aaslandcf0b2392021-01-06 01:02:43 +010022requires SQLite 3.7.15 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
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010029 con = 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
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010036 cur = con.cursor()
Georg Brandl116aa622007-08-15 14:28:22 +000037
38 # Create table
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010039 cur.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
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010043 cur.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
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010046 con.commit()
Georg Brandl116aa622007-08-15 14:28:22 +000047
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.
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010050 con.close()
Zachary Ware9d085622014-04-01 12:21:56 -050051
52The data you've saved is persistent and is available in subsequent sessions::
53
54 import sqlite3
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010055 con = sqlite3.connect('example.db')
56 cur = con.cursor()
Georg Brandl116aa622007-08-15 14:28:22 +000057
Georg Brandl9afde1c2007-11-01 20:32:30 +000058To retrieve data after executing a SELECT statement, you can either treat the
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000059cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
60retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandl9afde1c2007-11-01 20:32:30 +000061matching rows.
Georg Brandl116aa622007-08-15 14:28:22 +000062
63This example uses the iterator form::
64
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +010065 >>> for row in cur.execute('SELECT * FROM stocks ORDER BY price'):
Zachary Ware9d085622014-04-01 12:21:56 -050066 print(row)
67
Ezio Melottib5845052009-09-13 05:49:25 +000068 ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
69 ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
70 ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
Zachary Ware9d085622014-04-01 12:21:56 -050071 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
Georg Brandl116aa622007-08-15 14:28:22 +000072
73
Erlend Egeberg Aasland3386ca02021-04-14 14:28:55 +020074.. _sqlite3-placeholders:
75
76Usually your SQL operations will need to use values from Python variables. You
77shouldn't assemble your query using Python's string operations because doing so
78is insecure; it makes your program vulnerable to an SQL injection attack
79(see the `xkcd webcomic <https://xkcd.com/327/>`_ for a humorous example of
80what can go wrong)::
81
82 # Never do this -- insecure!
83 symbol = 'RHAT'
84 cur.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
85
86Instead, use the DB-API's parameter substitution. Put a placeholder wherever
87you want to use a value, and then provide a tuple of values as the second
88argument to the cursor's :meth:`~Cursor.execute` method. An SQL statement may
89use one of two kinds of placeholders: question marks (qmark style) or named
90placeholders (named style). For the qmark style, ``parameters`` must be a
91:term:`sequence <sequence>`. For the named style, it can be either a
92:term:`sequence <sequence>` or :class:`dict` instance. The length of the
93:term:`sequence <sequence>` must match the number of placeholders, or a
94:exc:`ProgrammingError` is raised. If a :class:`dict` is given, it must contain
95keys for all named parameters. Any extra items are ignored. Here's an example
96of both styles:
97
98.. literalinclude:: ../includes/sqlite3/execute_1.py
99
100
Georg Brandl116aa622007-08-15 14:28:22 +0000101.. seealso::
102
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300103 https://www.sqlite.org
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000104 The SQLite web page; the documentation describes the syntax and the
105 available data types for the supported SQL dialect.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Sanyam Khurana1b4587a2017-12-06 22:09:33 +0530107 https://www.w3schools.com/sql/
Zachary Ware9d085622014-04-01 12:21:56 -0500108 Tutorial, reference and examples for learning SQL syntax.
109
Georg Brandl116aa622007-08-15 14:28:22 +0000110 :pep:`249` - Database API Specification 2.0
111 PEP written by Marc-André Lemburg.
112
113
114.. _sqlite3-module-contents:
115
116Module functions and constants
117------------------------------
118
119
R David Murray3f7beb92013-01-10 20:18:21 -0500120.. data:: version
121
122 The version number of this module, as a string. This is not the version of
123 the SQLite library.
124
125
126.. data:: version_info
127
128 The version number of this module, as a tuple of integers. This is not the
129 version of the SQLite library.
130
131
132.. data:: sqlite_version
133
134 The version number of the run-time SQLite library, as a string.
135
136
137.. data:: sqlite_version_info
138
139 The version number of the run-time SQLite library, as a tuple of integers.
140
141
Georg Brandl116aa622007-08-15 14:28:22 +0000142.. data:: PARSE_DECLTYPES
143
144 This constant is meant to be used with the *detect_types* parameter of the
145 :func:`connect` function.
146
147 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000148 column it returns. It will parse out the first word of the declared type,
149 i. e. for "integer primary key", it will parse out "integer", or for
150 "number(10)" it will parse out "number". Then for that column, it will look
151 into the converters dictionary and use the converter function registered for
152 that type there.
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154
155.. data:: PARSE_COLNAMES
156
157 This constant is meant to be used with the *detect_types* parameter of the
158 :func:`connect` function.
159
160 Setting this makes the SQLite interface parse the column name for each column it
161 returns. It will look for a string formed [mytype] in there, and then decide
162 that 'mytype' is the type of the column. It will try to find an entry of
163 'mytype' in the converters dictionary and then use the converter function found
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000164 there to return the value. The column name found in :attr:`Cursor.description`
Serhiy Storchakab1465682020-03-21 15:53:28 +0200165 does not include the type, i. e. if you use something like
166 ``'as "Expiration date [datetime]"'`` in your SQL, then we will parse out
167 everything until the first ``'['`` for the column name and strip
168 the preceeding space: the column name would simply be "Expiration date".
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100171.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])
Georg Brandl116aa622007-08-15 14:28:22 +0000172
Anders Lorentsena22a1272017-11-07 01:47:43 +0100173 Opens a connection to the SQLite database file *database*. By default returns a
174 :class:`Connection` object, unless a custom *factory* is given.
175
176 *database* is a :term:`path-like object` giving the pathname (absolute or
177 relative to the current working directory) of the database file to be opened.
178 You can use ``":memory:"`` to open a database connection to a database that
179 resides in RAM instead of on disk.
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181 When a database is accessed by multiple connections, and one of the processes
182 modifies the database, the SQLite database is locked until that transaction is
183 committed. The *timeout* parameter specifies how long the connection should wait
184 for the lock to go away until raising an exception. The default for the timeout
185 parameter is 5.0 (five seconds).
186
187 For the *isolation_level* parameter, please see the
Berker Peksaga1bc2462016-09-07 04:02:41 +0300188 :attr:`~Connection.isolation_level` property of :class:`Connection` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
Georg Brandl3c127112013-10-06 12:38:44 +0200190 SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
Georg Brandl116aa622007-08-15 14:28:22 +0000191 you want to use other types you must add support for them yourself. The
192 *detect_types* parameter and the using custom **converters** registered with the
193 module-level :func:`register_converter` function allow you to easily do that.
194
195 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
196 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
sblondon09a36cd2020-12-19 23:52:39 +0100197 type detection on. Due to SQLite behaviour, types can't be detected for generated
198 fields (for example ``max(data)``), even when *detect_types* parameter is set. In
199 such case, the returned type is :class:`str`.
Georg Brandl116aa622007-08-15 14:28:22 +0000200
Senthil Kumaran7ee91942016-06-03 00:03:48 -0700201 By default, *check_same_thread* is :const:`True` and only the creating thread may
202 use the connection. If set :const:`False`, the returned connection may be shared
203 across multiple threads. When using multiple threads with the same connection
204 writing operations should be serialized by the user to avoid data corruption.
205
Georg Brandl116aa622007-08-15 14:28:22 +0000206 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
207 connect call. You can, however, subclass the :class:`Connection` class and make
208 :func:`connect` use your class instead by providing your class for the *factory*
209 parameter.
210
211 Consult the section :ref:`sqlite3-types` of this manual for details.
212
213 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
214 overhead. If you want to explicitly set the number of statements that are cached
215 for the connection, you can set the *cached_statements* parameter. The currently
216 implemented default is to cache 100 statements.
217
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100218 If *uri* is true, *database* is interpreted as a URI. This allows you
219 to specify options. For example, to open a database in read-only mode
220 you can use::
221
222 db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)
223
224 More information about this feature, including a list of recognized options, can
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300225 be found in the `SQLite URI documentation <https://www.sqlite.org/uri.html>`_.
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100226
Steve Dower44f91c32019-06-27 10:47:59 -0700227 .. audit-event:: sqlite3.connect database sqlite3.connect
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200228 .. audit-event:: sqlite3.connect/handle connection_handle sqlite3.connect
Steve Dower60419a72019-06-24 08:42:54 -0700229
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100230 .. versionchanged:: 3.4
231 Added the *uri* parameter.
232
Anders Lorentsena22a1272017-11-07 01:47:43 +0100233 .. versionchanged:: 3.7
234 *database* can now also be a :term:`path-like object`, not only a string.
235
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200236 .. versionchanged:: 3.10
237 Added the ``sqlite3.connect/handle`` auditing event.
238
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240.. function:: register_converter(typename, callable)
241
242 Registers a callable to convert a bytestring from the database into a custom
243 Python type. The callable will be invoked for all database values that are of
244 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
Sergey Fedoseev831c2972018-07-03 16:59:32 +0500245 function for how the type detection works. Note that *typename* and the name of
246 the type in your query are matched in case-insensitive manner.
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248
249.. function:: register_adapter(type, callable)
250
251 Registers a callable to convert the custom Python type *type* into one of
252 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000253 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000254 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256
257.. function:: complete_statement(sql)
258
259 Returns :const:`True` if the string *sql* contains one or more complete SQL
260 statements terminated by semicolons. It does not verify that the SQL is
261 syntactically correct, only that there are no unclosed string literals and the
262 statement is terminated by a semicolon.
263
264 This can be used to build a shell for SQLite, as in the following example:
265
266
267 .. literalinclude:: ../includes/sqlite3/complete_statement.py
268
269
270.. function:: enable_callback_tracebacks(flag)
271
272 By default you will not get any tracebacks in user-defined functions,
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200273 aggregates, converters, authorizer callbacks etc. If you want to debug them,
274 you can call this function with *flag* set to ``True``. Afterwards, you will
275 get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to
276 disable the feature again.
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278
279.. _sqlite3-connection-objects:
280
281Connection Objects
282------------------
283
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000284.. class:: Connection
285
286 A SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000287
R David Murray6db23352012-09-30 20:44:43 -0400288 .. attribute:: isolation_level
Georg Brandl116aa622007-08-15 14:28:22 +0000289
Berker Peksaga71fed02018-07-29 12:01:38 +0300290 Get or set the current default isolation level. :const:`None` for autocommit mode or
R David Murray6db23352012-09-30 20:44:43 -0400291 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
292 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000293
R David Murray6db23352012-09-30 20:44:43 -0400294 .. attribute:: in_transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000295
R David Murray6db23352012-09-30 20:44:43 -0400296 :const:`True` if a transaction is active (there are uncommitted changes),
297 :const:`False` otherwise. Read-only attribute.
R. David Murrayd35251d2010-06-01 01:32:12 +0000298
R David Murray6db23352012-09-30 20:44:43 -0400299 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300301 .. method:: cursor(factory=Cursor)
Georg Brandl116aa622007-08-15 14:28:22 +0000302
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300303 The cursor method accepts a single optional parameter *factory*. If
304 supplied, this must be a callable returning an instance of :class:`Cursor`
305 or its subclasses.
Georg Brandl116aa622007-08-15 14:28:22 +0000306
R David Murray6db23352012-09-30 20:44:43 -0400307 .. method:: commit()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000308
R David Murray6db23352012-09-30 20:44:43 -0400309 This method commits the current transaction. If you don't call this method,
310 anything you did since the last call to ``commit()`` is not visible from
311 other database connections. If you wonder why you don't see the data you've
312 written to the database, please check you didn't forget to call this method.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000313
R David Murray6db23352012-09-30 20:44:43 -0400314 .. method:: rollback()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000315
R David Murray6db23352012-09-30 20:44:43 -0400316 This method rolls back any changes to the database since the last call to
317 :meth:`commit`.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000318
R David Murray6db23352012-09-30 20:44:43 -0400319 .. method:: close()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000320
R David Murray6db23352012-09-30 20:44:43 -0400321 This closes the database connection. Note that this does not automatically
322 call :meth:`commit`. If you just close your database connection without
323 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000324
Berker Peksagc4154402016-06-12 13:41:47 +0300325 .. method:: execute(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000326
Berker Peksagc4154402016-06-12 13:41:47 +0300327 This is a nonstandard shortcut that creates a cursor object by calling
328 the :meth:`~Connection.cursor` method, calls the cursor's
329 :meth:`~Cursor.execute` method with the *parameters* given, and returns
330 the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000331
Berker Peksagc4154402016-06-12 13:41:47 +0300332 .. method:: executemany(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000333
Berker Peksagc4154402016-06-12 13:41:47 +0300334 This is a nonstandard shortcut that creates a cursor object by
335 calling the :meth:`~Connection.cursor` method, calls the cursor's
336 :meth:`~Cursor.executemany` method with the *parameters* given, and
337 returns the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
R David Murray6db23352012-09-30 20:44:43 -0400339 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Berker Peksagc4154402016-06-12 13:41:47 +0300341 This is a nonstandard shortcut that creates a cursor object by
342 calling the :meth:`~Connection.cursor` method, calls the cursor's
343 :meth:`~Cursor.executescript` method with the given *sql_script*, and
344 returns the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000345
Sergey Fedoseev08308582018-07-08 12:09:20 +0500346 .. method:: create_function(name, num_params, func, *, deterministic=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000347
R David Murray6db23352012-09-30 20:44:43 -0400348 Creates a user-defined function that you can later use from within SQL
349 statements under the function name *name*. *num_params* is the number of
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300350 parameters the function accepts (if *num_params* is -1, the function may
351 take any number of arguments), and *func* is a Python callable that is
Sergey Fedoseev08308582018-07-08 12:09:20 +0500352 called as the SQL function. If *deterministic* is true, the created function
353 is marked as `deterministic <https://sqlite.org/deterministic.html>`_, which
354 allows SQLite to perform additional optimizations. This flag is supported by
Marcin Niemirabc9aa812018-07-08 14:02:58 +0200355 SQLite 3.8.3 or higher, :exc:`NotSupportedError` will be raised if used
Sergey Fedoseev08308582018-07-08 12:09:20 +0500356 with older versions.
Georg Brandl116aa622007-08-15 14:28:22 +0000357
R David Murray6db23352012-09-30 20:44:43 -0400358 The function can return any of the types supported by SQLite: bytes, str, int,
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300359 float and ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Sergey Fedoseev08308582018-07-08 12:09:20 +0500361 .. versionchanged:: 3.8
362 The *deterministic* parameter was added.
363
R David Murray6db23352012-09-30 20:44:43 -0400364 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000365
R David Murray6db23352012-09-30 20:44:43 -0400366 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368
R David Murray6db23352012-09-30 20:44:43 -0400369 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl116aa622007-08-15 14:28:22 +0000370
R David Murray6db23352012-09-30 20:44:43 -0400371 Creates a user-defined aggregate function.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
R David Murray6db23352012-09-30 20:44:43 -0400373 The aggregate class must implement a ``step`` method, which accepts the number
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300374 of parameters *num_params* (if *num_params* is -1, the function may take
375 any number of arguments), and a ``finalize`` method which will return the
R David Murray6db23352012-09-30 20:44:43 -0400376 final result of the aggregate.
Georg Brandl116aa622007-08-15 14:28:22 +0000377
R David Murray6db23352012-09-30 20:44:43 -0400378 The ``finalize`` method can return any of the types supported by SQLite:
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300379 bytes, str, int, float and ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000380
R David Murray6db23352012-09-30 20:44:43 -0400381 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000382
R David Murray6db23352012-09-30 20:44:43 -0400383 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385
R David Murray6db23352012-09-30 20:44:43 -0400386 .. method:: create_collation(name, callable)
Georg Brandl116aa622007-08-15 14:28:22 +0000387
R David Murray6db23352012-09-30 20:44:43 -0400388 Creates a collation with the specified *name* and *callable*. The callable will
389 be passed two string arguments. It should return -1 if the first is ordered
390 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
391 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
392 your comparisons don't affect other SQL operations.
Georg Brandl116aa622007-08-15 14:28:22 +0000393
R David Murray6db23352012-09-30 20:44:43 -0400394 Note that the callable will get its parameters as Python bytestrings, which will
395 normally be encoded in UTF-8.
Georg Brandl116aa622007-08-15 14:28:22 +0000396
R David Murray6db23352012-09-30 20:44:43 -0400397 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl116aa622007-08-15 14:28:22 +0000398
R David Murray6db23352012-09-30 20:44:43 -0400399 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl116aa622007-08-15 14:28:22 +0000400
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300401 To remove a collation, call ``create_collation`` with ``None`` as callable::
Georg Brandl116aa622007-08-15 14:28:22 +0000402
R David Murray6db23352012-09-30 20:44:43 -0400403 con.create_collation("reverse", None)
Georg Brandl116aa622007-08-15 14:28:22 +0000404
405
R David Murray6db23352012-09-30 20:44:43 -0400406 .. method:: interrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000407
R David Murray6db23352012-09-30 20:44:43 -0400408 You can call this method from a different thread to abort any queries that might
409 be executing on the connection. The query will then abort and the caller will
410 get an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412
R David Murray6db23352012-09-30 20:44:43 -0400413 .. method:: set_authorizer(authorizer_callback)
Georg Brandl116aa622007-08-15 14:28:22 +0000414
R David Murray6db23352012-09-30 20:44:43 -0400415 This routine registers a callback. The callback is invoked for each attempt to
416 access a column of a table in the database. The callback should return
417 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
418 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
419 column should be treated as a NULL value. These constants are available in the
420 :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000421
R David Murray6db23352012-09-30 20:44:43 -0400422 The first argument to the callback signifies what kind of operation is to be
423 authorized. The second and third argument will be arguments or :const:`None`
424 depending on the first argument. The 4th argument is the name of the database
425 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
426 inner-most trigger or view that is responsible for the access attempt or
427 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl116aa622007-08-15 14:28:22 +0000428
R David Murray6db23352012-09-30 20:44:43 -0400429 Please consult the SQLite documentation about the possible values for the first
430 argument and the meaning of the second and third argument depending on the first
431 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000432
Georg Brandl116aa622007-08-15 14:28:22 +0000433
R David Murray6db23352012-09-30 20:44:43 -0400434 .. method:: set_progress_handler(handler, n)
Georg Brandl116aa622007-08-15 14:28:22 +0000435
R David Murray6db23352012-09-30 20:44:43 -0400436 This routine registers a callback. The callback is invoked for every *n*
437 instructions of the SQLite virtual machine. This is useful if you want to
438 get called from SQLite during long-running operations, for example to update
439 a GUI.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000440
R David Murray6db23352012-09-30 20:44:43 -0400441 If you want to clear any previously installed progress handler, call the
442 method with :const:`None` for *handler*.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000443
Simon Willisonac03c032017-11-02 07:34:12 -0700444 Returning a non-zero value from the handler function will terminate the
445 currently executing query and cause it to raise an :exc:`OperationalError`
446 exception.
447
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000448
R David Murray842ca5f2012-09-30 20:49:19 -0400449 .. method:: set_trace_callback(trace_callback)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000450
R David Murray842ca5f2012-09-30 20:49:19 -0400451 Registers *trace_callback* to be called for each SQL statement that is
452 actually executed by the SQLite backend.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200453
R David Murray842ca5f2012-09-30 20:49:19 -0400454 The only argument passed to the callback is the statement (as string) that
455 is being executed. The return value of the callback is ignored. Note that
456 the backend does not only run statements passed to the :meth:`Cursor.execute`
457 methods. Other sources include the transaction management of the Python
458 module and the execution of triggers defined in the current database.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200459
R David Murray842ca5f2012-09-30 20:49:19 -0400460 Passing :const:`None` as *trace_callback* will disable the trace callback.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200461
R David Murray842ca5f2012-09-30 20:49:19 -0400462 .. versionadded:: 3.3
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200463
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200464
R David Murray6db23352012-09-30 20:44:43 -0400465 .. method:: enable_load_extension(enabled)
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200466
R David Murray6db23352012-09-30 20:44:43 -0400467 This routine allows/disallows the SQLite engine to load SQLite extensions
468 from shared libraries. SQLite extensions can define new functions,
469 aggregates or whole new virtual table implementations. One well-known
470 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000471
R David Murray6db23352012-09-30 20:44:43 -0400472 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000473
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200474 .. audit-event:: sqlite3.enable_load_extension connection,enabled sqlite3.enable_load_extension
475
R David Murray6db23352012-09-30 20:44:43 -0400476 .. versionadded:: 3.2
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200477
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200478 .. versionchanged:: 3.10
479 Added the ``sqlite3.enable_load_extension`` auditing event.
480
R David Murray6db23352012-09-30 20:44:43 -0400481 .. literalinclude:: ../includes/sqlite3/load_extension.py
Georg Brandl67b21b72010-08-17 15:07:14 +0000482
R David Murray6db23352012-09-30 20:44:43 -0400483 .. method:: load_extension(path)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000484
R David Murray6db23352012-09-30 20:44:43 -0400485 This routine loads a SQLite extension from a shared library. You have to
486 enable extension loading with :meth:`enable_load_extension` before you can
487 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000488
R David Murray6db23352012-09-30 20:44:43 -0400489 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000490
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200491 .. audit-event:: sqlite3.load_extension connection,path sqlite3.load_extension
492
R David Murray6db23352012-09-30 20:44:43 -0400493 .. versionadded:: 3.2
Gerhard Häringe0941c52010-10-03 21:47:06 +0000494
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +0200495 .. versionchanged:: 3.10
496 Added the ``sqlite3.load_extension`` auditing event.
497
R David Murray6db23352012-09-30 20:44:43 -0400498 .. attribute:: row_factory
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200499
R David Murray6db23352012-09-30 20:44:43 -0400500 You can change this attribute to a callable that accepts the cursor and the
501 original row as a tuple and will return the real result row. This way, you can
502 implement more advanced ways of returning results, such as returning an object
503 that can also access columns by name.
Georg Brandl116aa622007-08-15 14:28:22 +0000504
R David Murray6db23352012-09-30 20:44:43 -0400505 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000506
R David Murray6db23352012-09-30 20:44:43 -0400507 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000508
R David Murray6db23352012-09-30 20:44:43 -0400509 If returning a tuple doesn't suffice and you want name-based access to
510 columns, you should consider setting :attr:`row_factory` to the
511 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
512 index-based and case-insensitive name-based access to columns with almost no
513 memory overhead. It will probably be better than your own custom
514 dictionary-based approach or even a db_row based solution.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
R David Murray6db23352012-09-30 20:44:43 -0400516 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Georg Brandl116aa622007-08-15 14:28:22 +0000518
R David Murray6db23352012-09-30 20:44:43 -0400519 .. attribute:: text_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000520
R David Murray6db23352012-09-30 20:44:43 -0400521 Using this attribute you can control what objects are returned for the ``TEXT``
522 data type. By default, this attribute is set to :class:`str` and the
523 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
524 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
R David Murray6db23352012-09-30 20:44:43 -0400526 You can also set it to any other callable that accepts a single bytestring
527 parameter and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000528
R David Murray6db23352012-09-30 20:44:43 -0400529 See the following example code for illustration:
Georg Brandl116aa622007-08-15 14:28:22 +0000530
R David Murray6db23352012-09-30 20:44:43 -0400531 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000532
533
R David Murray6db23352012-09-30 20:44:43 -0400534 .. attribute:: total_changes
Georg Brandl116aa622007-08-15 14:28:22 +0000535
R David Murray6db23352012-09-30 20:44:43 -0400536 Returns the total number of database rows that have been modified, inserted, or
537 deleted since the database connection was opened.
Georg Brandl116aa622007-08-15 14:28:22 +0000538
539
Berker Peksag557a0632016-03-27 18:46:18 +0300540 .. method:: iterdump
Christian Heimesbbe741d2008-03-28 10:53:29 +0000541
R David Murray6db23352012-09-30 20:44:43 -0400542 Returns an iterator to dump the database in an SQL text format. Useful when
543 saving an in-memory database for later restoration. This function provides
544 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
545 shell.
Christian Heimesbbe741d2008-03-28 10:53:29 +0000546
R David Murray6db23352012-09-30 20:44:43 -0400547 Example::
Christian Heimesbbe741d2008-03-28 10:53:29 +0000548
R David Murray6db23352012-09-30 20:44:43 -0400549 # Convert file existing_db.db to SQL dump file dump.sql
Berker Peksag557a0632016-03-27 18:46:18 +0300550 import sqlite3
Christian Heimesbbe741d2008-03-28 10:53:29 +0000551
R David Murray6db23352012-09-30 20:44:43 -0400552 con = sqlite3.connect('existing_db.db')
553 with open('dump.sql', 'w') as f:
554 for line in con.iterdump():
555 f.write('%s\n' % line)
Xtreak287b84d2019-05-20 03:22:20 +0530556 con.close()
Christian Heimesbbe741d2008-03-28 10:53:29 +0000557
558
Erlend Egeberg Aaslandabba83b2020-12-27 23:35:17 +0100559 .. method:: backup(target, *, pages=-1, progress=None, name="main", sleep=0.250)
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100560
561 This method makes a backup of a SQLite database even while it's being accessed
562 by other clients, or concurrently by the same connection. The copy will be
563 written into the mandatory argument *target*, that must be another
564 :class:`Connection` instance.
565
566 By default, or when *pages* is either ``0`` or a negative integer, the entire
567 database is copied in a single step; otherwise the method performs a loop
568 copying up to *pages* pages at a time.
569
570 If *progress* is specified, it must either be ``None`` or a callable object that
571 will be executed at each iteration with three integer arguments, respectively
572 the *status* of the last iteration, the *remaining* number of pages still to be
573 copied and the *total* number of pages.
574
575 The *name* argument specifies the database name that will be copied: it must be
576 a string containing either ``"main"``, the default, to indicate the main
577 database, ``"temp"`` to indicate the temporary database or the name specified
578 after the ``AS`` keyword in an ``ATTACH DATABASE`` statement for an attached
579 database.
580
581 The *sleep* argument specifies the number of seconds to sleep by between
582 successive attempts to backup remaining pages, can be specified either as an
583 integer or a floating point value.
584
585 Example 1, copy an existing database into another::
586
587 import sqlite3
588
589 def progress(status, remaining, total):
590 print(f'Copied {total-remaining} of {total} pages...')
591
592 con = sqlite3.connect('existing_db.db')
Xtreak287b84d2019-05-20 03:22:20 +0530593 bck = sqlite3.connect('backup.db')
594 with bck:
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100595 con.backup(bck, pages=1, progress=progress)
Xtreak287b84d2019-05-20 03:22:20 +0530596 bck.close()
597 con.close()
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100598
599 Example 2, copy an existing database into a transient copy::
600
601 import sqlite3
602
603 source = sqlite3.connect('existing_db.db')
604 dest = sqlite3.connect(':memory:')
605 source.backup(dest)
606
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100607 .. versionadded:: 3.7
608
609
Georg Brandl116aa622007-08-15 14:28:22 +0000610.. _sqlite3-cursor-objects:
611
612Cursor Objects
613--------------
614
Georg Brandl96115fb22010-10-17 09:33:24 +0000615.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000616
Georg Brandl96115fb22010-10-17 09:33:24 +0000617 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000618
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200619 .. index:: single: ? (question mark); in SQL statements
620 .. index:: single: : (colon); in SQL statements
621
Berker Peksagc4154402016-06-12 13:41:47 +0300622 .. method:: execute(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000623
Erlend Egeberg Aasland3386ca02021-04-14 14:28:55 +0200624 Executes an SQL statement. Values may be bound to the statement using
625 :ref:`placeholders <sqlite3-placeholders>`.
Georg Brandl116aa622007-08-15 14:28:22 +0000626
R David Murray6db23352012-09-30 20:44:43 -0400627 :meth:`execute` will only execute a single SQL statement. If you try to execute
Berker Peksag7d92f892016-08-25 00:50:24 +0300628 more than one statement with it, it will raise a :exc:`.Warning`. Use
R David Murray6db23352012-09-30 20:44:43 -0400629 :meth:`executescript` if you want to execute multiple SQL statements with one
630 call.
Georg Brandl116aa622007-08-15 14:28:22 +0000631
632
R David Murray6db23352012-09-30 20:44:43 -0400633 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl116aa622007-08-15 14:28:22 +0000634
Erlend Egeberg Aasland3386ca02021-04-14 14:28:55 +0200635 Executes a :ref:`parameterized <sqlite3-placeholders>` SQL command
636 against all parameter sequences or mappings found in the sequence
637 *seq_of_parameters*. The :mod:`sqlite3` module also allows using an
638 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000639
R David Murray6db23352012-09-30 20:44:43 -0400640 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000641
R David Murray6db23352012-09-30 20:44:43 -0400642 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000643
R David Murray6db23352012-09-30 20:44:43 -0400644 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl116aa622007-08-15 14:28:22 +0000645
646
R David Murray6db23352012-09-30 20:44:43 -0400647 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000648
R David Murray6db23352012-09-30 20:44:43 -0400649 This is a nonstandard convenience method for executing multiple SQL statements
650 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
651 gets as a parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Berker Peksagc4154402016-06-12 13:41:47 +0300653 *sql_script* can be an instance of :class:`str`.
Georg Brandl116aa622007-08-15 14:28:22 +0000654
R David Murray6db23352012-09-30 20:44:43 -0400655 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000656
R David Murray6db23352012-09-30 20:44:43 -0400657 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl116aa622007-08-15 14:28:22 +0000658
659
R David Murray6db23352012-09-30 20:44:43 -0400660 .. method:: fetchone()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000661
R David Murray6db23352012-09-30 20:44:43 -0400662 Fetches the next row of a query result set, returning a single sequence,
663 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000664
665
R David Murray6db23352012-09-30 20:44:43 -0400666 .. method:: fetchmany(size=cursor.arraysize)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000667
R David Murray6db23352012-09-30 20:44:43 -0400668 Fetches the next set of rows of a query result, returning a list. An empty
669 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000670
R David Murray6db23352012-09-30 20:44:43 -0400671 The number of rows to fetch per call is specified by the *size* parameter.
672 If it is not given, the cursor's arraysize determines the number of rows
673 to be fetched. The method should try to fetch as many rows as indicated by
674 the size parameter. If this is not possible due to the specified number of
675 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000676
R David Murray6db23352012-09-30 20:44:43 -0400677 Note there are performance considerations involved with the *size* parameter.
678 For optimal performance, it is usually best to use the arraysize attribute.
679 If the *size* parameter is used, then it is best for it to retain the same
680 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000681
R David Murray6db23352012-09-30 20:44:43 -0400682 .. method:: fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000683
R David Murray6db23352012-09-30 20:44:43 -0400684 Fetches all (remaining) rows of a query result, returning a list. Note that
685 the cursor's arraysize attribute can affect the performance of this operation.
686 An empty list is returned when no rows are available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000687
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300688 .. method:: close()
689
690 Close the cursor now (rather than whenever ``__del__`` is called).
691
Berker Peksaged789f92016-08-25 00:45:07 +0300692 The cursor will be unusable from this point forward; a :exc:`ProgrammingError`
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300693 exception will be raised if any operation is attempted with the cursor.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000694
R David Murray6db23352012-09-30 20:44:43 -0400695 .. attribute:: rowcount
Georg Brandl116aa622007-08-15 14:28:22 +0000696
R David Murray6db23352012-09-30 20:44:43 -0400697 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
698 attribute, the database engine's own support for the determination of "rows
699 affected"/"rows selected" is quirky.
Georg Brandl116aa622007-08-15 14:28:22 +0000700
R David Murray6db23352012-09-30 20:44:43 -0400701 For :meth:`executemany` statements, the number of modifications are summed up
702 into :attr:`rowcount`.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
R David Murray6db23352012-09-30 20:44:43 -0400704 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
705 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
706 last operation is not determinable by the interface". This includes ``SELECT``
707 statements because we cannot determine the number of rows a query produced
708 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000709
R David Murray6db23352012-09-30 20:44:43 -0400710 .. attribute:: lastrowid
Gerhard Häringd3372792008-03-29 19:13:55 +0000711
R David Murray6db23352012-09-30 20:44:43 -0400712 This read-only attribute provides the rowid of the last modified row. It is
Berker Peksage0b70cd2016-06-14 15:25:36 +0300713 only set if you issued an ``INSERT`` or a ``REPLACE`` statement using the
714 :meth:`execute` method. For operations other than ``INSERT`` or
715 ``REPLACE`` or when :meth:`executemany` is called, :attr:`lastrowid` is
716 set to :const:`None`.
717
718 If the ``INSERT`` or ``REPLACE`` statement failed to insert the previous
719 successful rowid is returned.
720
721 .. versionchanged:: 3.6
722 Added support for the ``REPLACE`` statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000723
csabella02e12132017-04-04 01:16:14 -0400724 .. attribute:: arraysize
725
726 Read/write attribute that controls the number of rows returned by :meth:`fetchmany`.
727 The default value is 1 which means a single row would be fetched per call.
728
R David Murray6db23352012-09-30 20:44:43 -0400729 .. attribute:: description
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000730
R David Murray6db23352012-09-30 20:44:43 -0400731 This read-only attribute provides the column names of the last query. To
732 remain compatible with the Python DB API, it returns a 7-tuple for each
733 column where the last six items of each tuple are :const:`None`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000734
R David Murray6db23352012-09-30 20:44:43 -0400735 It is set for ``SELECT`` statements without any matching rows as well.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000736
Ezio Melotti62564db2016-03-18 20:10:36 +0200737 .. attribute:: connection
738
739 This read-only attribute provides the SQLite database :class:`Connection`
740 used by the :class:`Cursor` object. A :class:`Cursor` object created by
741 calling :meth:`con.cursor() <Connection.cursor>` will have a
742 :attr:`connection` attribute that refers to *con*::
743
744 >>> con = sqlite3.connect(":memory:")
745 >>> cur = con.cursor()
746 >>> cur.connection == con
747 True
748
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000749.. _sqlite3-row-objects:
750
751Row Objects
752-----------
753
754.. class:: Row
755
756 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000757 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000758 It tries to mimic a tuple in most of its features.
759
760 It supports mapping access by column name and index, iteration,
761 representation, equality testing and :func:`len`.
762
763 If two :class:`Row` objects have exactly the same columns and their
764 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000765
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000766 .. method:: keys
767
R David Murray092135e2014-06-05 15:16:38 -0400768 This method returns a list of column names. Immediately after a query,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000769 it is the first member of each tuple in :attr:`Cursor.description`.
770
Serhiy Storchaka72e731c2015-03-31 13:33:11 +0300771 .. versionchanged:: 3.5
772 Added support of slicing.
773
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000774Let's assume we initialize a table as in the example given above::
775
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +0100776 con = sqlite3.connect(":memory:")
777 cur = con.cursor()
778 cur.execute('''create table stocks
Senthil Kumaran946eb862011-07-03 10:17:22 -0700779 (date text, trans text, symbol text,
780 qty real, price real)''')
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +0100781 cur.execute("""insert into stocks
782 values ('2006-01-05','BUY','RHAT',100,35.14)""")
783 con.commit()
784 cur.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000785
786Now we plug :class:`Row` in::
787
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +0100788 >>> con.row_factory = sqlite3.Row
789 >>> cur = con.cursor()
790 >>> cur.execute('select * from stocks')
Senthil Kumaran946eb862011-07-03 10:17:22 -0700791 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
Erlend Egeberg Aasland40d1b832021-03-04 16:46:14 +0100792 >>> r = cur.fetchone()
Senthil Kumaran946eb862011-07-03 10:17:22 -0700793 >>> type(r)
794 <class 'sqlite3.Row'>
795 >>> tuple(r)
796 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
797 >>> len(r)
798 5
799 >>> r[2]
800 'RHAT'
801 >>> r.keys()
802 ['date', 'trans', 'symbol', 'qty', 'price']
803 >>> r['qty']
804 100.0
805 >>> for member in r:
806 ... print(member)
807 ...
808 2006-01-05
809 BUY
810 RHAT
811 100.0
812 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000813
814
Berker Peksaged789f92016-08-25 00:45:07 +0300815.. _sqlite3-exceptions:
816
817Exceptions
818----------
819
820.. exception:: Warning
821
822 A subclass of :exc:`Exception`.
823
824.. exception:: Error
825
826 The base class of the other exceptions in this module. It is a subclass
827 of :exc:`Exception`.
828
829.. exception:: DatabaseError
830
831 Exception raised for errors that are related to the database.
832
833.. exception:: IntegrityError
834
835 Exception raised when the relational integrity of the database is affected,
836 e.g. a foreign key check fails. It is a subclass of :exc:`DatabaseError`.
837
838.. exception:: ProgrammingError
839
840 Exception raised for programming errors, e.g. table not found or already
841 exists, syntax error in the SQL statement, wrong number of parameters
842 specified, etc. It is a subclass of :exc:`DatabaseError`.
843
Zackery Spytz71ede002018-06-13 03:09:31 -0600844.. exception:: OperationalError
845
846 Exception raised for errors that are related to the database's operation
847 and not necessarily under the control of the programmer, e.g. an unexpected
848 disconnect occurs, the data source name is not found, a transaction could
849 not be processed, etc. It is a subclass of :exc:`DatabaseError`.
850
Marcin Niemirabc9aa812018-07-08 14:02:58 +0200851.. exception:: NotSupportedError
852
853 Exception raised in case a method or database API was used which is not
854 supported by the database, e.g. calling the :meth:`~Connection.rollback`
855 method on a connection that does not support transaction or has
856 transactions turned off. It is a subclass of :exc:`DatabaseError`.
857
Berker Peksaged789f92016-08-25 00:45:07 +0300858
Georg Brandl116aa622007-08-15 14:28:22 +0000859.. _sqlite3-types:
860
861SQLite and Python types
862-----------------------
863
864
865Introduction
866^^^^^^^^^^^^
867
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000868SQLite natively supports the following types: ``NULL``, ``INTEGER``,
869``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000870
871The following Python types can thus be sent to SQLite without any problem:
872
Georg Brandlf6945182008-02-01 11:56:49 +0000873+-------------------------------+-------------+
874| Python type | SQLite type |
875+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000876| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000877+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000878| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000879+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000880| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000881+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000882| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000883+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000884| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000885+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000886
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000887
Georg Brandl116aa622007-08-15 14:28:22 +0000888This is how SQLite types are converted to Python types by default:
889
Zachary Ware9d085622014-04-01 12:21:56 -0500890+-------------+----------------------------------------------+
891| SQLite type | Python type |
892+=============+==============================================+
893| ``NULL`` | :const:`None` |
894+-------------+----------------------------------------------+
895| ``INTEGER`` | :class:`int` |
896+-------------+----------------------------------------------+
897| ``REAL`` | :class:`float` |
898+-------------+----------------------------------------------+
899| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
900| | :class:`str` by default |
901+-------------+----------------------------------------------+
902| ``BLOB`` | :class:`bytes` |
903+-------------+----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000904
905The type system of the :mod:`sqlite3` module is extensible in two ways: you can
906store additional Python types in a SQLite database via object adaptation, and
907you can let the :mod:`sqlite3` module convert SQLite types to different Python
908types via converters.
909
910
911Using adapters to store additional Python types in SQLite databases
912^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
913
914As described before, SQLite supports only a limited set of types natively. To
915use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000916sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000917str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000918
Georg Brandl116aa622007-08-15 14:28:22 +0000919There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
920type to one of the supported ones.
921
922
923Letting your object adapt itself
924""""""""""""""""""""""""""""""""
925
926This is a good approach if you write the class yourself. Let's suppose you have
927a class like this::
928
Éric Araujo28053fb2010-11-22 03:09:19 +0000929 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000930 def __init__(self, x, y):
931 self.x, self.y = x, y
932
933Now you want to store the point in a single SQLite column. First you'll have to
Naglis441416c2020-05-06 19:51:43 +0000934choose one of the supported types to be used for representing the point.
Georg Brandl116aa622007-08-15 14:28:22 +0000935Let's just use str and separate the coordinates using a semicolon. Then you need
936to give your class a method ``__conform__(self, protocol)`` which must return
937the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
938
939.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
940
941
942Registering an adapter callable
943"""""""""""""""""""""""""""""""
944
945The other possibility is to create a function that converts the type to the
946string representation and register the function with :meth:`register_adapter`.
947
Georg Brandl116aa622007-08-15 14:28:22 +0000948.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
949
950The :mod:`sqlite3` module has two default adapters for Python's built-in
951:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
952we want to store :class:`datetime.datetime` objects not in ISO representation,
953but as a Unix timestamp.
954
955.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
956
957
958Converting SQLite values to custom Python types
959^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
960
961Writing an adapter lets you send custom Python types to SQLite. But to make it
962really useful we need to make the Python to SQLite to Python roundtrip work.
963
964Enter converters.
965
966Let's go back to the :class:`Point` class. We stored the x and y coordinates
967separated via semicolons as strings in SQLite.
968
969First, we'll define a converter function that accepts the string as a parameter
970and constructs a :class:`Point` object from it.
971
972.. note::
973
Zachary Ware9d085622014-04-01 12:21:56 -0500974 Converter functions **always** get called with a :class:`bytes` object, no
975 matter under which data type you sent the value to SQLite.
Georg Brandl116aa622007-08-15 14:28:22 +0000976
Georg Brandl116aa622007-08-15 14:28:22 +0000977::
978
979 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200980 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +0000981 return Point(x, y)
982
983Now you need to make the :mod:`sqlite3` module know that what you select from
984the database is actually a point. There are two ways of doing this:
985
986* Implicitly via the declared type
987
988* Explicitly via the column name
989
990Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
991for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
992
993The following example illustrates both approaches.
994
995.. literalinclude:: ../includes/sqlite3/converter_point.py
996
997
998Default adapters and converters
999^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1000
1001There are default adapters for the date and datetime types in the datetime
1002module. They will be sent as ISO dates/ISO timestamps to SQLite.
1003
1004The default converters are registered under the name "date" for
1005:class:`datetime.date` and under the name "timestamp" for
1006:class:`datetime.datetime`.
1007
1008This way, you can use date/timestamps from Python without any additional
1009fiddling in most cases. The format of the adapters is also compatible with the
1010experimental SQLite date/time functions.
1011
1012The following example demonstrates this.
1013
1014.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
1015
Petri Lehtinen5f794092013-02-26 21:32:02 +02001016If a timestamp stored in SQLite has a fractional part longer than 6
1017numbers, its value will be truncated to microsecond precision by the
1018timestamp converter.
1019
Georg Brandl116aa622007-08-15 14:28:22 +00001020
1021.. _sqlite3-controlling-transactions:
1022
1023Controlling Transactions
1024------------------------
1025
Berker Peksaga71fed02018-07-29 12:01:38 +03001026The underlying ``sqlite3`` library operates in ``autocommit`` mode by default,
1027but the Python :mod:`sqlite3` module by default does not.
1028
1029``autocommit`` mode means that statements that modify the database take effect
1030immediately. A ``BEGIN`` or ``SAVEPOINT`` statement disables ``autocommit``
1031mode, and a ``COMMIT``, a ``ROLLBACK``, or a ``RELEASE`` that ends the
1032outermost transaction, turns ``autocommit`` mode back on.
1033
1034The Python :mod:`sqlite3` module by default issues a ``BEGIN`` statement
1035implicitly before a Data Modification Language (DML) statement (i.e.
Berker Peksagab994ed2016-09-11 12:57:15 +03001036``INSERT``/``UPDATE``/``DELETE``/``REPLACE``).
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Berker Peksaga71fed02018-07-29 12:01:38 +03001038You can control which kind of ``BEGIN`` statements :mod:`sqlite3` implicitly
1039executes via the *isolation_level* parameter to the :func:`connect`
Georg Brandl116aa622007-08-15 14:28:22 +00001040call, or via the :attr:`isolation_level` property of connections.
Berker Peksaga71fed02018-07-29 12:01:38 +03001041If you specify no *isolation_level*, a plain ``BEGIN`` is used, which is
1042equivalent to specifying ``DEFERRED``. Other possible values are ``IMMEDIATE``
1043and ``EXCLUSIVE``.
Georg Brandl116aa622007-08-15 14:28:22 +00001044
Berker Peksaga71fed02018-07-29 12:01:38 +03001045You can disable the :mod:`sqlite3` module's implicit transaction management by
1046setting :attr:`isolation_level` to ``None``. This will leave the underlying
1047``sqlite3`` library operating in ``autocommit`` mode. You can then completely
1048control the transaction state by explicitly issuing ``BEGIN``, ``ROLLBACK``,
1049``SAVEPOINT``, and ``RELEASE`` statements in your code.
Berker Peksagfe70d922017-02-26 18:31:12 +03001050
Berker Peksagab994ed2016-09-11 12:57:15 +03001051.. versionchanged:: 3.6
1052 :mod:`sqlite3` used to implicitly commit an open transaction before DDL
1053 statements. This is no longer the case.
Georg Brandl116aa622007-08-15 14:28:22 +00001054
1055
Georg Brandl8a1e4c42009-05-25 21:13:36 +00001056Using :mod:`sqlite3` efficiently
1057--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001058
1059
1060Using shortcut methods
1061^^^^^^^^^^^^^^^^^^^^^^
1062
1063Using the nonstandard :meth:`execute`, :meth:`executemany` and
1064:meth:`executescript` methods of the :class:`Connection` object, your code can
1065be written more concisely because you don't have to create the (often
1066superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
1067objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001068objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +00001069directly using only a single call on the :class:`Connection` object.
1070
1071.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
1072
1073
1074Accessing columns by name instead of by index
1075^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1076
Georg Brandl22b34312009-07-26 14:54:51 +00001077One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +00001078:class:`sqlite3.Row` class designed to be used as a row factory.
1079
1080Rows wrapped with this class can be accessed both by index (like tuples) and
1081case-insensitively by name:
1082
1083.. literalinclude:: ../includes/sqlite3/rowclass.py
1084
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +00001085
1086Using the connection as a context manager
1087^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1088
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +00001089Connection objects can be used as context managers
1090that automatically commit or rollback transactions. In the event of an
1091exception, the transaction is rolled back; otherwise, the transaction is
1092committed:
1093
1094.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +00001095
1096
Gerhard Häringe0941c52010-10-03 21:47:06 +00001097.. rubric:: Footnotes
1098
1099.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumaran946eb862011-07-03 10:17:22 -07001100 default, because some platforms (notably Mac OS X) have SQLite
1101 libraries which are compiled without this feature. To get loadable
Victor Stinner85918e42021-04-12 23:27:35 +02001102 extension support, you must pass the
1103 :option:`--enable-loadable-sqlite-extensions` option to configure.