blob: 9e3c56b5f9189e4e502e4603548ee16a0a4175e3 [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
21compliant with the DB-API 2.0 specification described by :pep:`249`.
Georg Brandl116aa622007-08-15 14:28:22 +000022
23To use the module, you must first create a :class:`Connection` object that
24represents the database. Here the data will be stored in the
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +010025:file:`example.db` file::
Georg Brandl116aa622007-08-15 14:28:22 +000026
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020027 import sqlite3
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +010028 conn = sqlite3.connect('example.db')
Georg Brandl116aa622007-08-15 14:28:22 +000029
30You can also supply the special name ``:memory:`` to create a database in RAM.
31
32Once you have a :class:`Connection`, you can create a :class:`Cursor` object
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000033and call its :meth:`~Cursor.execute` method to perform SQL commands::
Georg Brandl116aa622007-08-15 14:28:22 +000034
35 c = conn.cursor()
36
37 # Create table
Zachary Ware9d085622014-04-01 12:21:56 -050038 c.execute('''CREATE TABLE stocks
39 (date text, trans text, symbol text, qty real, price real)''')
Georg Brandl116aa622007-08-15 14:28:22 +000040
41 # Insert a row of data
Zachary Ware9d085622014-04-01 12:21:56 -050042 c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
Georg Brandl116aa622007-08-15 14:28:22 +000043
44 # Save (commit) the changes
45 conn.commit()
46
Zachary Ware9d085622014-04-01 12:21:56 -050047 # We can also close the connection if we are done with it.
48 # Just be sure any changes have been committed or they will be lost.
49 conn.close()
50
51The data you've saved is persistent and is available in subsequent sessions::
52
53 import sqlite3
54 conn = sqlite3.connect('example.db')
55 c = conn.cursor()
Georg Brandl116aa622007-08-15 14:28:22 +000056
57Usually your SQL operations will need to use values from Python variables. You
58shouldn't assemble your query using Python's string operations because doing so
Zachary Ware9d085622014-04-01 12:21:56 -050059is insecure; it makes your program vulnerable to an SQL injection attack
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030060(see https://xkcd.com/327/ for humorous example of what can go wrong).
Georg Brandl116aa622007-08-15 14:28:22 +000061
62Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
63wherever you want to use a value, and then provide a tuple of values as the
Georg Brandl8a1e4c42009-05-25 21:13:36 +000064second argument to the cursor's :meth:`~Cursor.execute` method. (Other database
65modules may use a different placeholder, such as ``%s`` or ``:1``.) For
66example::
Georg Brandl116aa622007-08-15 14:28:22 +000067
68 # Never do this -- insecure!
Zachary Ware9d085622014-04-01 12:21:56 -050069 symbol = 'RHAT'
70 c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
Georg Brandl116aa622007-08-15 14:28:22 +000071
72 # Do this instead
Zachary Ware9d085622014-04-01 12:21:56 -050073 t = ('RHAT',)
74 c.execute('SELECT * FROM stocks WHERE symbol=?', t)
75 print(c.fetchone())
Georg Brandl116aa622007-08-15 14:28:22 +000076
Zachary Ware9d085622014-04-01 12:21:56 -050077 # Larger example that inserts many records at a time
78 purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
79 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
80 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
81 ]
82 c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
Georg Brandl116aa622007-08-15 14:28:22 +000083
Georg Brandl9afde1c2007-11-01 20:32:30 +000084To retrieve data after executing a SELECT statement, you can either treat the
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000085cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
86retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandl9afde1c2007-11-01 20:32:30 +000087matching rows.
Georg Brandl116aa622007-08-15 14:28:22 +000088
89This example uses the iterator form::
90
Zachary Ware9d085622014-04-01 12:21:56 -050091 >>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
92 print(row)
93
Ezio Melottib5845052009-09-13 05:49:25 +000094 ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
95 ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
96 ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
Zachary Ware9d085622014-04-01 12:21:56 -050097 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
Georg Brandl116aa622007-08-15 14:28:22 +000098
99
100.. seealso::
101
Benjamin Peterson216e47d2014-01-16 09:52:38 -0500102 https://github.com/ghaering/pysqlite
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000103 The pysqlite web page -- sqlite3 is developed externally under the name
104 "pysqlite".
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300106 https://www.sqlite.org
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000107 The SQLite web page; the documentation describes the syntax and the
108 available data types for the supported SQL dialect.
Georg Brandl116aa622007-08-15 14:28:22 +0000109
Sanyam Khurana1b4587a2017-12-06 22:09:33 +0530110 https://www.w3schools.com/sql/
Zachary Ware9d085622014-04-01 12:21:56 -0500111 Tutorial, reference and examples for learning SQL syntax.
112
Georg Brandl116aa622007-08-15 14:28:22 +0000113 :pep:`249` - Database API Specification 2.0
114 PEP written by Marc-André Lemburg.
115
116
117.. _sqlite3-module-contents:
118
119Module functions and constants
120------------------------------
121
122
R David Murray3f7beb92013-01-10 20:18:21 -0500123.. data:: version
124
125 The version number of this module, as a string. This is not the version of
126 the SQLite library.
127
128
129.. data:: version_info
130
131 The version number of this module, as a tuple of integers. This is not the
132 version of the SQLite library.
133
134
135.. data:: sqlite_version
136
137 The version number of the run-time SQLite library, as a string.
138
139
140.. data:: sqlite_version_info
141
142 The version number of the run-time SQLite library, as a tuple of integers.
143
144
Georg Brandl116aa622007-08-15 14:28:22 +0000145.. data:: PARSE_DECLTYPES
146
147 This constant is meant to be used with the *detect_types* parameter of the
148 :func:`connect` function.
149
150 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000151 column it returns. It will parse out the first word of the declared type,
152 i. e. for "integer primary key", it will parse out "integer", or for
153 "number(10)" it will parse out "number". Then for that column, it will look
154 into the converters dictionary and use the converter function registered for
155 that type there.
Georg Brandl116aa622007-08-15 14:28:22 +0000156
157
158.. data:: PARSE_COLNAMES
159
160 This constant is meant to be used with the *detect_types* parameter of the
161 :func:`connect` function.
162
163 Setting this makes the SQLite interface parse the column name for each column it
164 returns. It will look for a string formed [mytype] in there, and then decide
165 that 'mytype' is the type of the column. It will try to find an entry of
166 'mytype' in the converters dictionary and then use the converter function found
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000167 there to return the value. The column name found in :attr:`Cursor.description`
Georg Brandl116aa622007-08-15 14:28:22 +0000168 is only the first word of the column name, i. e. if you use something like
169 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
170 first blank for the column name: the column name would simply be "x".
171
172
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100173.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Anders Lorentsena22a1272017-11-07 01:47:43 +0100175 Opens a connection to the SQLite database file *database*. By default returns a
176 :class:`Connection` object, unless a custom *factory* is given.
177
178 *database* is a :term:`path-like object` giving the pathname (absolute or
179 relative to the current working directory) of the database file to be opened.
180 You can use ``":memory:"`` to open a database connection to a database that
181 resides in RAM instead of on disk.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183 When a database is accessed by multiple connections, and one of the processes
184 modifies the database, the SQLite database is locked until that transaction is
185 committed. The *timeout* parameter specifies how long the connection should wait
186 for the lock to go away until raising an exception. The default for the timeout
187 parameter is 5.0 (five seconds).
188
189 For the *isolation_level* parameter, please see the
Berker Peksaga1bc2462016-09-07 04:02:41 +0300190 :attr:`~Connection.isolation_level` property of :class:`Connection` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Georg Brandl3c127112013-10-06 12:38:44 +0200192 SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
Georg Brandl116aa622007-08-15 14:28:22 +0000193 you want to use other types you must add support for them yourself. The
194 *detect_types* parameter and the using custom **converters** registered with the
195 module-level :func:`register_converter` function allow you to easily do that.
196
197 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
198 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
199 type detection on.
200
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
227 .. versionchanged:: 3.4
228 Added the *uri* parameter.
229
Anders Lorentsena22a1272017-11-07 01:47:43 +0100230 .. versionchanged:: 3.7
231 *database* can now also be a :term:`path-like object`, not only a string.
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234.. function:: register_converter(typename, callable)
235
236 Registers a callable to convert a bytestring from the database into a custom
237 Python type. The callable will be invoked for all database values that are of
238 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
Sergey Fedoseev831c2972018-07-03 16:59:32 +0500239 function for how the type detection works. Note that *typename* and the name of
240 the type in your query are matched in case-insensitive manner.
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242
243.. function:: register_adapter(type, callable)
244
245 Registers a callable to convert the custom Python type *type* into one of
246 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000247 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000248 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250
251.. function:: complete_statement(sql)
252
253 Returns :const:`True` if the string *sql* contains one or more complete SQL
254 statements terminated by semicolons. It does not verify that the SQL is
255 syntactically correct, only that there are no unclosed string literals and the
256 statement is terminated by a semicolon.
257
258 This can be used to build a shell for SQLite, as in the following example:
259
260
261 .. literalinclude:: ../includes/sqlite3/complete_statement.py
262
263
264.. function:: enable_callback_tracebacks(flag)
265
266 By default you will not get any tracebacks in user-defined functions,
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200267 aggregates, converters, authorizer callbacks etc. If you want to debug them,
268 you can call this function with *flag* set to ``True``. Afterwards, you will
269 get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to
270 disable the feature again.
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272
273.. _sqlite3-connection-objects:
274
275Connection Objects
276------------------
277
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000278.. class:: Connection
279
280 A SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000281
R David Murray6db23352012-09-30 20:44:43 -0400282 .. attribute:: isolation_level
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Berker Peksaga71fed02018-07-29 12:01:38 +0300284 Get or set the current default isolation level. :const:`None` for autocommit mode or
R David Murray6db23352012-09-30 20:44:43 -0400285 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
286 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
R David Murray6db23352012-09-30 20:44:43 -0400288 .. attribute:: in_transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000289
R David Murray6db23352012-09-30 20:44:43 -0400290 :const:`True` if a transaction is active (there are uncommitted changes),
291 :const:`False` otherwise. Read-only attribute.
R. David Murrayd35251d2010-06-01 01:32:12 +0000292
R David Murray6db23352012-09-30 20:44:43 -0400293 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000294
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300295 .. method:: cursor(factory=Cursor)
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300297 The cursor method accepts a single optional parameter *factory*. If
298 supplied, this must be a callable returning an instance of :class:`Cursor`
299 or its subclasses.
Georg Brandl116aa622007-08-15 14:28:22 +0000300
R David Murray6db23352012-09-30 20:44:43 -0400301 .. method:: commit()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000302
R David Murray6db23352012-09-30 20:44:43 -0400303 This method commits the current transaction. If you don't call this method,
304 anything you did since the last call to ``commit()`` is not visible from
305 other database connections. If you wonder why you don't see the data you've
306 written to the database, please check you didn't forget to call this method.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000307
R David Murray6db23352012-09-30 20:44:43 -0400308 .. method:: rollback()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000309
R David Murray6db23352012-09-30 20:44:43 -0400310 This method rolls back any changes to the database since the last call to
311 :meth:`commit`.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000312
R David Murray6db23352012-09-30 20:44:43 -0400313 .. method:: close()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000314
R David Murray6db23352012-09-30 20:44:43 -0400315 This closes the database connection. Note that this does not automatically
316 call :meth:`commit`. If you just close your database connection without
317 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000318
Berker Peksagc4154402016-06-12 13:41:47 +0300319 .. method:: execute(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000320
Berker Peksagc4154402016-06-12 13:41:47 +0300321 This is a nonstandard shortcut that creates a cursor object by calling
322 the :meth:`~Connection.cursor` method, calls the cursor's
323 :meth:`~Cursor.execute` method with the *parameters* given, and returns
324 the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000325
Berker Peksagc4154402016-06-12 13:41:47 +0300326 .. method:: executemany(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000327
Berker Peksagc4154402016-06-12 13:41:47 +0300328 This is a nonstandard shortcut that creates a cursor object by
329 calling the :meth:`~Connection.cursor` method, calls the cursor's
330 :meth:`~Cursor.executemany` method with the *parameters* given, and
331 returns the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000332
R David Murray6db23352012-09-30 20:44:43 -0400333 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000334
Berker Peksagc4154402016-06-12 13:41:47 +0300335 This is a nonstandard shortcut that creates a cursor object by
336 calling the :meth:`~Connection.cursor` method, calls the cursor's
337 :meth:`~Cursor.executescript` method with the given *sql_script*, and
338 returns the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000339
Sergey Fedoseev08308582018-07-08 12:09:20 +0500340 .. method:: create_function(name, num_params, func, *, deterministic=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000341
R David Murray6db23352012-09-30 20:44:43 -0400342 Creates a user-defined function that you can later use from within SQL
343 statements under the function name *name*. *num_params* is the number of
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300344 parameters the function accepts (if *num_params* is -1, the function may
345 take any number of arguments), and *func* is a Python callable that is
Sergey Fedoseev08308582018-07-08 12:09:20 +0500346 called as the SQL function. If *deterministic* is true, the created function
347 is marked as `deterministic <https://sqlite.org/deterministic.html>`_, which
348 allows SQLite to perform additional optimizations. This flag is supported by
Marcin Niemirabc9aa812018-07-08 14:02:58 +0200349 SQLite 3.8.3 or higher, :exc:`NotSupportedError` will be raised if used
Sergey Fedoseev08308582018-07-08 12:09:20 +0500350 with older versions.
Georg Brandl116aa622007-08-15 14:28:22 +0000351
R David Murray6db23352012-09-30 20:44:43 -0400352 The function can return any of the types supported by SQLite: bytes, str, int,
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300353 float and ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000354
Sergey Fedoseev08308582018-07-08 12:09:20 +0500355 .. versionchanged:: 3.8
356 The *deterministic* parameter was added.
357
R David Murray6db23352012-09-30 20:44:43 -0400358 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000359
R David Murray6db23352012-09-30 20:44:43 -0400360 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362
R David Murray6db23352012-09-30 20:44:43 -0400363 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl116aa622007-08-15 14:28:22 +0000364
R David Murray6db23352012-09-30 20:44:43 -0400365 Creates a user-defined aggregate function.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
R David Murray6db23352012-09-30 20:44:43 -0400367 The aggregate class must implement a ``step`` method, which accepts the number
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300368 of parameters *num_params* (if *num_params* is -1, the function may take
369 any number of arguments), and a ``finalize`` method which will return the
R David Murray6db23352012-09-30 20:44:43 -0400370 final result of the aggregate.
Georg Brandl116aa622007-08-15 14:28:22 +0000371
R David Murray6db23352012-09-30 20:44:43 -0400372 The ``finalize`` method can return any of the types supported by SQLite:
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300373 bytes, str, int, float and ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000374
R David Murray6db23352012-09-30 20:44:43 -0400375 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000376
R David Murray6db23352012-09-30 20:44:43 -0400377 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379
R David Murray6db23352012-09-30 20:44:43 -0400380 .. method:: create_collation(name, callable)
Georg Brandl116aa622007-08-15 14:28:22 +0000381
R David Murray6db23352012-09-30 20:44:43 -0400382 Creates a collation with the specified *name* and *callable*. The callable will
383 be passed two string arguments. It should return -1 if the first is ordered
384 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
385 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
386 your comparisons don't affect other SQL operations.
Georg Brandl116aa622007-08-15 14:28:22 +0000387
R David Murray6db23352012-09-30 20:44:43 -0400388 Note that the callable will get its parameters as Python bytestrings, which will
389 normally be encoded in UTF-8.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
R David Murray6db23352012-09-30 20:44:43 -0400391 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl116aa622007-08-15 14:28:22 +0000392
R David Murray6db23352012-09-30 20:44:43 -0400393 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl116aa622007-08-15 14:28:22 +0000394
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300395 To remove a collation, call ``create_collation`` with ``None`` as callable::
Georg Brandl116aa622007-08-15 14:28:22 +0000396
R David Murray6db23352012-09-30 20:44:43 -0400397 con.create_collation("reverse", None)
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399
R David Murray6db23352012-09-30 20:44:43 -0400400 .. method:: interrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000401
R David Murray6db23352012-09-30 20:44:43 -0400402 You can call this method from a different thread to abort any queries that might
403 be executing on the connection. The query will then abort and the caller will
404 get an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000405
406
R David Murray6db23352012-09-30 20:44:43 -0400407 .. method:: set_authorizer(authorizer_callback)
Georg Brandl116aa622007-08-15 14:28:22 +0000408
R David Murray6db23352012-09-30 20:44:43 -0400409 This routine registers a callback. The callback is invoked for each attempt to
410 access a column of a table in the database. The callback should return
411 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
412 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
413 column should be treated as a NULL value. These constants are available in the
414 :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000415
R David Murray6db23352012-09-30 20:44:43 -0400416 The first argument to the callback signifies what kind of operation is to be
417 authorized. The second and third argument will be arguments or :const:`None`
418 depending on the first argument. The 4th argument is the name of the database
419 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
420 inner-most trigger or view that is responsible for the access attempt or
421 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl116aa622007-08-15 14:28:22 +0000422
R David Murray6db23352012-09-30 20:44:43 -0400423 Please consult the SQLite documentation about the possible values for the first
424 argument and the meaning of the second and third argument depending on the first
425 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Georg Brandl116aa622007-08-15 14:28:22 +0000427
R David Murray6db23352012-09-30 20:44:43 -0400428 .. method:: set_progress_handler(handler, n)
Georg Brandl116aa622007-08-15 14:28:22 +0000429
R David Murray6db23352012-09-30 20:44:43 -0400430 This routine registers a callback. The callback is invoked for every *n*
431 instructions of the SQLite virtual machine. This is useful if you want to
432 get called from SQLite during long-running operations, for example to update
433 a GUI.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000434
R David Murray6db23352012-09-30 20:44:43 -0400435 If you want to clear any previously installed progress handler, call the
436 method with :const:`None` for *handler*.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000437
Simon Willisonac03c032017-11-02 07:34:12 -0700438 Returning a non-zero value from the handler function will terminate the
439 currently executing query and cause it to raise an :exc:`OperationalError`
440 exception.
441
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000442
R David Murray842ca5f2012-09-30 20:49:19 -0400443 .. method:: set_trace_callback(trace_callback)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000444
R David Murray842ca5f2012-09-30 20:49:19 -0400445 Registers *trace_callback* to be called for each SQL statement that is
446 actually executed by the SQLite backend.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200447
R David Murray842ca5f2012-09-30 20:49:19 -0400448 The only argument passed to the callback is the statement (as string) that
449 is being executed. The return value of the callback is ignored. Note that
450 the backend does not only run statements passed to the :meth:`Cursor.execute`
451 methods. Other sources include the transaction management of the Python
452 module and the execution of triggers defined in the current database.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200453
R David Murray842ca5f2012-09-30 20:49:19 -0400454 Passing :const:`None` as *trace_callback* will disable the trace callback.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200455
R David Murray842ca5f2012-09-30 20:49:19 -0400456 .. versionadded:: 3.3
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200457
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200458
R David Murray6db23352012-09-30 20:44:43 -0400459 .. method:: enable_load_extension(enabled)
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200460
R David Murray6db23352012-09-30 20:44:43 -0400461 This routine allows/disallows the SQLite engine to load SQLite extensions
462 from shared libraries. SQLite extensions can define new functions,
463 aggregates or whole new virtual table implementations. One well-known
464 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000465
R David Murray6db23352012-09-30 20:44:43 -0400466 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000467
R David Murray6db23352012-09-30 20:44:43 -0400468 .. versionadded:: 3.2
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200469
R David Murray6db23352012-09-30 20:44:43 -0400470 .. literalinclude:: ../includes/sqlite3/load_extension.py
Georg Brandl67b21b72010-08-17 15:07:14 +0000471
R David Murray6db23352012-09-30 20:44:43 -0400472 .. method:: load_extension(path)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000473
R David Murray6db23352012-09-30 20:44:43 -0400474 This routine loads a SQLite extension from a shared library. You have to
475 enable extension loading with :meth:`enable_load_extension` before you can
476 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000477
R David Murray6db23352012-09-30 20:44:43 -0400478 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000479
R David Murray6db23352012-09-30 20:44:43 -0400480 .. versionadded:: 3.2
Gerhard Häringe0941c52010-10-03 21:47:06 +0000481
R David Murray6db23352012-09-30 20:44:43 -0400482 .. attribute:: row_factory
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200483
R David Murray6db23352012-09-30 20:44:43 -0400484 You can change this attribute to a callable that accepts the cursor and the
485 original row as a tuple and will return the real result row. This way, you can
486 implement more advanced ways of returning results, such as returning an object
487 that can also access columns by name.
Georg Brandl116aa622007-08-15 14:28:22 +0000488
R David Murray6db23352012-09-30 20:44:43 -0400489 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000490
R David Murray6db23352012-09-30 20:44:43 -0400491 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000492
R David Murray6db23352012-09-30 20:44:43 -0400493 If returning a tuple doesn't suffice and you want name-based access to
494 columns, you should consider setting :attr:`row_factory` to the
495 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
496 index-based and case-insensitive name-based access to columns with almost no
497 memory overhead. It will probably be better than your own custom
498 dictionary-based approach or even a db_row based solution.
Georg Brandl116aa622007-08-15 14:28:22 +0000499
R David Murray6db23352012-09-30 20:44:43 -0400500 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000501
Georg Brandl116aa622007-08-15 14:28:22 +0000502
R David Murray6db23352012-09-30 20:44:43 -0400503 .. attribute:: text_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000504
R David Murray6db23352012-09-30 20:44:43 -0400505 Using this attribute you can control what objects are returned for the ``TEXT``
506 data type. By default, this attribute is set to :class:`str` and the
507 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
508 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000509
R David Murray6db23352012-09-30 20:44:43 -0400510 You can also set it to any other callable that accepts a single bytestring
511 parameter and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000512
R David Murray6db23352012-09-30 20:44:43 -0400513 See the following example code for illustration:
Georg Brandl116aa622007-08-15 14:28:22 +0000514
R David Murray6db23352012-09-30 20:44:43 -0400515 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000516
517
R David Murray6db23352012-09-30 20:44:43 -0400518 .. attribute:: total_changes
Georg Brandl116aa622007-08-15 14:28:22 +0000519
R David Murray6db23352012-09-30 20:44:43 -0400520 Returns the total number of database rows that have been modified, inserted, or
521 deleted since the database connection was opened.
Georg Brandl116aa622007-08-15 14:28:22 +0000522
523
Berker Peksag557a0632016-03-27 18:46:18 +0300524 .. method:: iterdump
Christian Heimesbbe741d2008-03-28 10:53:29 +0000525
R David Murray6db23352012-09-30 20:44:43 -0400526 Returns an iterator to dump the database in an SQL text format. Useful when
527 saving an in-memory database for later restoration. This function provides
528 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
529 shell.
Christian Heimesbbe741d2008-03-28 10:53:29 +0000530
R David Murray6db23352012-09-30 20:44:43 -0400531 Example::
Christian Heimesbbe741d2008-03-28 10:53:29 +0000532
R David Murray6db23352012-09-30 20:44:43 -0400533 # Convert file existing_db.db to SQL dump file dump.sql
Berker Peksag557a0632016-03-27 18:46:18 +0300534 import sqlite3
Christian Heimesbbe741d2008-03-28 10:53:29 +0000535
R David Murray6db23352012-09-30 20:44:43 -0400536 con = sqlite3.connect('existing_db.db')
537 with open('dump.sql', 'w') as f:
538 for line in con.iterdump():
539 f.write('%s\n' % line)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000540
541
Emanuele Gaifasd7aed412018-03-10 23:08:31 +0100542 .. method:: backup(target, *, pages=0, progress=None, name="main", sleep=0.250)
543
544 This method makes a backup of a SQLite database even while it's being accessed
545 by other clients, or concurrently by the same connection. The copy will be
546 written into the mandatory argument *target*, that must be another
547 :class:`Connection` instance.
548
549 By default, or when *pages* is either ``0`` or a negative integer, the entire
550 database is copied in a single step; otherwise the method performs a loop
551 copying up to *pages* pages at a time.
552
553 If *progress* is specified, it must either be ``None`` or a callable object that
554 will be executed at each iteration with three integer arguments, respectively
555 the *status* of the last iteration, the *remaining* number of pages still to be
556 copied and the *total* number of pages.
557
558 The *name* argument specifies the database name that will be copied: it must be
559 a string containing either ``"main"``, the default, to indicate the main
560 database, ``"temp"`` to indicate the temporary database or the name specified
561 after the ``AS`` keyword in an ``ATTACH DATABASE`` statement for an attached
562 database.
563
564 The *sleep* argument specifies the number of seconds to sleep by between
565 successive attempts to backup remaining pages, can be specified either as an
566 integer or a floating point value.
567
568 Example 1, copy an existing database into another::
569
570 import sqlite3
571
572 def progress(status, remaining, total):
573 print(f'Copied {total-remaining} of {total} pages...')
574
575 con = sqlite3.connect('existing_db.db')
576 with sqlite3.connect('backup.db') as bck:
577 con.backup(bck, pages=1, progress=progress)
578
579 Example 2, copy an existing database into a transient copy::
580
581 import sqlite3
582
583 source = sqlite3.connect('existing_db.db')
584 dest = sqlite3.connect(':memory:')
585 source.backup(dest)
586
587 Availability: SQLite 3.6.11 or higher
588
589 .. versionadded:: 3.7
590
591
Georg Brandl116aa622007-08-15 14:28:22 +0000592.. _sqlite3-cursor-objects:
593
594Cursor Objects
595--------------
596
Georg Brandl96115fb22010-10-17 09:33:24 +0000597.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000598
Georg Brandl96115fb22010-10-17 09:33:24 +0000599 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000600
Berker Peksagc4154402016-06-12 13:41:47 +0300601 .. method:: execute(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000602
Zachary Ware9d085622014-04-01 12:21:56 -0500603 Executes an SQL statement. The SQL statement may be parameterized (i. e.
R David Murray6db23352012-09-30 20:44:43 -0400604 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
605 kinds of placeholders: question marks (qmark style) and named placeholders
606 (named style).
Georg Brandl116aa622007-08-15 14:28:22 +0000607
R David Murray6db23352012-09-30 20:44:43 -0400608 Here's an example of both styles:
Georg Brandl116aa622007-08-15 14:28:22 +0000609
R David Murray6db23352012-09-30 20:44:43 -0400610 .. literalinclude:: ../includes/sqlite3/execute_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000611
R David Murray6db23352012-09-30 20:44:43 -0400612 :meth:`execute` will only execute a single SQL statement. If you try to execute
Berker Peksag7d92f892016-08-25 00:50:24 +0300613 more than one statement with it, it will raise a :exc:`.Warning`. Use
R David Murray6db23352012-09-30 20:44:43 -0400614 :meth:`executescript` if you want to execute multiple SQL statements with one
615 call.
Georg Brandl116aa622007-08-15 14:28:22 +0000616
617
R David Murray6db23352012-09-30 20:44:43 -0400618 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl116aa622007-08-15 14:28:22 +0000619
R David Murray6db23352012-09-30 20:44:43 -0400620 Executes an SQL command against all parameter sequences or mappings found in
Berker Peksagc4154402016-06-12 13:41:47 +0300621 the sequence *seq_of_parameters*. The :mod:`sqlite3` module also allows
622 using an :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000623
R David Murray6db23352012-09-30 20:44:43 -0400624 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000625
R David Murray6db23352012-09-30 20:44:43 -0400626 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000627
R David Murray6db23352012-09-30 20:44:43 -0400628 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl116aa622007-08-15 14:28:22 +0000629
630
R David Murray6db23352012-09-30 20:44:43 -0400631 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000632
R David Murray6db23352012-09-30 20:44:43 -0400633 This is a nonstandard convenience method for executing multiple SQL statements
634 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
635 gets as a parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000636
Berker Peksagc4154402016-06-12 13:41:47 +0300637 *sql_script* can be an instance of :class:`str`.
Georg Brandl116aa622007-08-15 14:28:22 +0000638
R David Murray6db23352012-09-30 20:44:43 -0400639 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000640
R David Murray6db23352012-09-30 20:44:43 -0400641 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl116aa622007-08-15 14:28:22 +0000642
643
R David Murray6db23352012-09-30 20:44:43 -0400644 .. method:: fetchone()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000645
R David Murray6db23352012-09-30 20:44:43 -0400646 Fetches the next row of a query result set, returning a single sequence,
647 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000648
649
R David Murray6db23352012-09-30 20:44:43 -0400650 .. method:: fetchmany(size=cursor.arraysize)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000651
R David Murray6db23352012-09-30 20:44:43 -0400652 Fetches the next set of rows of a query result, returning a list. An empty
653 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000654
R David Murray6db23352012-09-30 20:44:43 -0400655 The number of rows to fetch per call is specified by the *size* parameter.
656 If it is not given, the cursor's arraysize determines the number of rows
657 to be fetched. The method should try to fetch as many rows as indicated by
658 the size parameter. If this is not possible due to the specified number of
659 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000660
R David Murray6db23352012-09-30 20:44:43 -0400661 Note there are performance considerations involved with the *size* parameter.
662 For optimal performance, it is usually best to use the arraysize attribute.
663 If the *size* parameter is used, then it is best for it to retain the same
664 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000665
R David Murray6db23352012-09-30 20:44:43 -0400666 .. method:: fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000667
R David Murray6db23352012-09-30 20:44:43 -0400668 Fetches all (remaining) rows of a query result, returning a list. Note that
669 the cursor's arraysize attribute can affect the performance of this operation.
670 An empty list is returned when no rows are available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000671
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300672 .. method:: close()
673
674 Close the cursor now (rather than whenever ``__del__`` is called).
675
Berker Peksaged789f92016-08-25 00:45:07 +0300676 The cursor will be unusable from this point forward; a :exc:`ProgrammingError`
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300677 exception will be raised if any operation is attempted with the cursor.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000678
R David Murray6db23352012-09-30 20:44:43 -0400679 .. attribute:: rowcount
Georg Brandl116aa622007-08-15 14:28:22 +0000680
R David Murray6db23352012-09-30 20:44:43 -0400681 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
682 attribute, the database engine's own support for the determination of "rows
683 affected"/"rows selected" is quirky.
Georg Brandl116aa622007-08-15 14:28:22 +0000684
R David Murray6db23352012-09-30 20:44:43 -0400685 For :meth:`executemany` statements, the number of modifications are summed up
686 into :attr:`rowcount`.
Georg Brandl116aa622007-08-15 14:28:22 +0000687
R David Murray6db23352012-09-30 20:44:43 -0400688 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
689 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
690 last operation is not determinable by the interface". This includes ``SELECT``
691 statements because we cannot determine the number of rows a query produced
692 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000693
R David Murray6db23352012-09-30 20:44:43 -0400694 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
695 you make a ``DELETE FROM table`` without any condition.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000696
R David Murray6db23352012-09-30 20:44:43 -0400697 .. attribute:: lastrowid
Gerhard Häringd3372792008-03-29 19:13:55 +0000698
R David Murray6db23352012-09-30 20:44:43 -0400699 This read-only attribute provides the rowid of the last modified row. It is
Berker Peksage0b70cd2016-06-14 15:25:36 +0300700 only set if you issued an ``INSERT`` or a ``REPLACE`` statement using the
701 :meth:`execute` method. For operations other than ``INSERT`` or
702 ``REPLACE`` or when :meth:`executemany` is called, :attr:`lastrowid` is
703 set to :const:`None`.
704
705 If the ``INSERT`` or ``REPLACE`` statement failed to insert the previous
706 successful rowid is returned.
707
708 .. versionchanged:: 3.6
709 Added support for the ``REPLACE`` statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000710
csabella02e12132017-04-04 01:16:14 -0400711 .. attribute:: arraysize
712
713 Read/write attribute that controls the number of rows returned by :meth:`fetchmany`.
714 The default value is 1 which means a single row would be fetched per call.
715
R David Murray6db23352012-09-30 20:44:43 -0400716 .. attribute:: description
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000717
R David Murray6db23352012-09-30 20:44:43 -0400718 This read-only attribute provides the column names of the last query. To
719 remain compatible with the Python DB API, it returns a 7-tuple for each
720 column where the last six items of each tuple are :const:`None`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000721
R David Murray6db23352012-09-30 20:44:43 -0400722 It is set for ``SELECT`` statements without any matching rows as well.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000723
Ezio Melotti62564db2016-03-18 20:10:36 +0200724 .. attribute:: connection
725
726 This read-only attribute provides the SQLite database :class:`Connection`
727 used by the :class:`Cursor` object. A :class:`Cursor` object created by
728 calling :meth:`con.cursor() <Connection.cursor>` will have a
729 :attr:`connection` attribute that refers to *con*::
730
731 >>> con = sqlite3.connect(":memory:")
732 >>> cur = con.cursor()
733 >>> cur.connection == con
734 True
735
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000736.. _sqlite3-row-objects:
737
738Row Objects
739-----------
740
741.. class:: Row
742
743 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000744 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000745 It tries to mimic a tuple in most of its features.
746
747 It supports mapping access by column name and index, iteration,
748 representation, equality testing and :func:`len`.
749
750 If two :class:`Row` objects have exactly the same columns and their
751 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000752
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000753 .. method:: keys
754
R David Murray092135e2014-06-05 15:16:38 -0400755 This method returns a list of column names. Immediately after a query,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000756 it is the first member of each tuple in :attr:`Cursor.description`.
757
Serhiy Storchaka72e731c2015-03-31 13:33:11 +0300758 .. versionchanged:: 3.5
759 Added support of slicing.
760
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000761Let's assume we initialize a table as in the example given above::
762
Senthil Kumaran946eb862011-07-03 10:17:22 -0700763 conn = sqlite3.connect(":memory:")
764 c = conn.cursor()
765 c.execute('''create table stocks
766 (date text, trans text, symbol text,
767 qty real, price real)''')
768 c.execute("""insert into stocks
769 values ('2006-01-05','BUY','RHAT',100,35.14)""")
770 conn.commit()
771 c.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000772
773Now we plug :class:`Row` in::
774
Senthil Kumaran946eb862011-07-03 10:17:22 -0700775 >>> conn.row_factory = sqlite3.Row
776 >>> c = conn.cursor()
777 >>> c.execute('select * from stocks')
778 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
779 >>> r = c.fetchone()
780 >>> type(r)
781 <class 'sqlite3.Row'>
782 >>> tuple(r)
783 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
784 >>> len(r)
785 5
786 >>> r[2]
787 'RHAT'
788 >>> r.keys()
789 ['date', 'trans', 'symbol', 'qty', 'price']
790 >>> r['qty']
791 100.0
792 >>> for member in r:
793 ... print(member)
794 ...
795 2006-01-05
796 BUY
797 RHAT
798 100.0
799 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000800
801
Berker Peksaged789f92016-08-25 00:45:07 +0300802.. _sqlite3-exceptions:
803
804Exceptions
805----------
806
807.. exception:: Warning
808
809 A subclass of :exc:`Exception`.
810
811.. exception:: Error
812
813 The base class of the other exceptions in this module. It is a subclass
814 of :exc:`Exception`.
815
816.. exception:: DatabaseError
817
818 Exception raised for errors that are related to the database.
819
820.. exception:: IntegrityError
821
822 Exception raised when the relational integrity of the database is affected,
823 e.g. a foreign key check fails. It is a subclass of :exc:`DatabaseError`.
824
825.. exception:: ProgrammingError
826
827 Exception raised for programming errors, e.g. table not found or already
828 exists, syntax error in the SQL statement, wrong number of parameters
829 specified, etc. It is a subclass of :exc:`DatabaseError`.
830
Zackery Spytz71ede002018-06-13 03:09:31 -0600831.. exception:: OperationalError
832
833 Exception raised for errors that are related to the database's operation
834 and not necessarily under the control of the programmer, e.g. an unexpected
835 disconnect occurs, the data source name is not found, a transaction could
836 not be processed, etc. It is a subclass of :exc:`DatabaseError`.
837
Marcin Niemirabc9aa812018-07-08 14:02:58 +0200838.. exception:: NotSupportedError
839
840 Exception raised in case a method or database API was used which is not
841 supported by the database, e.g. calling the :meth:`~Connection.rollback`
842 method on a connection that does not support transaction or has
843 transactions turned off. It is a subclass of :exc:`DatabaseError`.
844
Berker Peksaged789f92016-08-25 00:45:07 +0300845
Georg Brandl116aa622007-08-15 14:28:22 +0000846.. _sqlite3-types:
847
848SQLite and Python types
849-----------------------
850
851
852Introduction
853^^^^^^^^^^^^
854
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000855SQLite natively supports the following types: ``NULL``, ``INTEGER``,
856``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000857
858The following Python types can thus be sent to SQLite without any problem:
859
Georg Brandlf6945182008-02-01 11:56:49 +0000860+-------------------------------+-------------+
861| Python type | SQLite type |
862+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000863| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000864+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000865| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000866+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000867| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000868+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000869| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000870+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000871| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000872+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000873
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000874
Georg Brandl116aa622007-08-15 14:28:22 +0000875This is how SQLite types are converted to Python types by default:
876
Zachary Ware9d085622014-04-01 12:21:56 -0500877+-------------+----------------------------------------------+
878| SQLite type | Python type |
879+=============+==============================================+
880| ``NULL`` | :const:`None` |
881+-------------+----------------------------------------------+
882| ``INTEGER`` | :class:`int` |
883+-------------+----------------------------------------------+
884| ``REAL`` | :class:`float` |
885+-------------+----------------------------------------------+
886| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
887| | :class:`str` by default |
888+-------------+----------------------------------------------+
889| ``BLOB`` | :class:`bytes` |
890+-------------+----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000891
892The type system of the :mod:`sqlite3` module is extensible in two ways: you can
893store additional Python types in a SQLite database via object adaptation, and
894you can let the :mod:`sqlite3` module convert SQLite types to different Python
895types via converters.
896
897
898Using adapters to store additional Python types in SQLite databases
899^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
900
901As described before, SQLite supports only a limited set of types natively. To
902use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000903sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000904str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000905
Georg Brandl116aa622007-08-15 14:28:22 +0000906There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
907type to one of the supported ones.
908
909
910Letting your object adapt itself
911""""""""""""""""""""""""""""""""
912
913This is a good approach if you write the class yourself. Let's suppose you have
914a class like this::
915
Éric Araujo28053fb2010-11-22 03:09:19 +0000916 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000917 def __init__(self, x, y):
918 self.x, self.y = x, y
919
920Now you want to store the point in a single SQLite column. First you'll have to
921choose one of the supported types first to be used for representing the point.
922Let's just use str and separate the coordinates using a semicolon. Then you need
923to give your class a method ``__conform__(self, protocol)`` which must return
924the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
925
926.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
927
928
929Registering an adapter callable
930"""""""""""""""""""""""""""""""
931
932The other possibility is to create a function that converts the type to the
933string representation and register the function with :meth:`register_adapter`.
934
Georg Brandl116aa622007-08-15 14:28:22 +0000935.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
936
937The :mod:`sqlite3` module has two default adapters for Python's built-in
938:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
939we want to store :class:`datetime.datetime` objects not in ISO representation,
940but as a Unix timestamp.
941
942.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
943
944
945Converting SQLite values to custom Python types
946^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
947
948Writing an adapter lets you send custom Python types to SQLite. But to make it
949really useful we need to make the Python to SQLite to Python roundtrip work.
950
951Enter converters.
952
953Let's go back to the :class:`Point` class. We stored the x and y coordinates
954separated via semicolons as strings in SQLite.
955
956First, we'll define a converter function that accepts the string as a parameter
957and constructs a :class:`Point` object from it.
958
959.. note::
960
Zachary Ware9d085622014-04-01 12:21:56 -0500961 Converter functions **always** get called with a :class:`bytes` object, no
962 matter under which data type you sent the value to SQLite.
Georg Brandl116aa622007-08-15 14:28:22 +0000963
Georg Brandl116aa622007-08-15 14:28:22 +0000964::
965
966 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200967 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +0000968 return Point(x, y)
969
970Now you need to make the :mod:`sqlite3` module know that what you select from
971the database is actually a point. There are two ways of doing this:
972
973* Implicitly via the declared type
974
975* Explicitly via the column name
976
977Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
978for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
979
980The following example illustrates both approaches.
981
982.. literalinclude:: ../includes/sqlite3/converter_point.py
983
984
985Default adapters and converters
986^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
987
988There are default adapters for the date and datetime types in the datetime
989module. They will be sent as ISO dates/ISO timestamps to SQLite.
990
991The default converters are registered under the name "date" for
992:class:`datetime.date` and under the name "timestamp" for
993:class:`datetime.datetime`.
994
995This way, you can use date/timestamps from Python without any additional
996fiddling in most cases. The format of the adapters is also compatible with the
997experimental SQLite date/time functions.
998
999The following example demonstrates this.
1000
1001.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
1002
Petri Lehtinen5f794092013-02-26 21:32:02 +02001003If a timestamp stored in SQLite has a fractional part longer than 6
1004numbers, its value will be truncated to microsecond precision by the
1005timestamp converter.
1006
Georg Brandl116aa622007-08-15 14:28:22 +00001007
1008.. _sqlite3-controlling-transactions:
1009
1010Controlling Transactions
1011------------------------
1012
Berker Peksaga71fed02018-07-29 12:01:38 +03001013The underlying ``sqlite3`` library operates in ``autocommit`` mode by default,
1014but the Python :mod:`sqlite3` module by default does not.
1015
1016``autocommit`` mode means that statements that modify the database take effect
1017immediately. A ``BEGIN`` or ``SAVEPOINT`` statement disables ``autocommit``
1018mode, and a ``COMMIT``, a ``ROLLBACK``, or a ``RELEASE`` that ends the
1019outermost transaction, turns ``autocommit`` mode back on.
1020
1021The Python :mod:`sqlite3` module by default issues a ``BEGIN`` statement
1022implicitly before a Data Modification Language (DML) statement (i.e.
Berker Peksagab994ed2016-09-11 12:57:15 +03001023``INSERT``/``UPDATE``/``DELETE``/``REPLACE``).
Georg Brandl116aa622007-08-15 14:28:22 +00001024
Berker Peksaga71fed02018-07-29 12:01:38 +03001025You can control which kind of ``BEGIN`` statements :mod:`sqlite3` implicitly
1026executes via the *isolation_level* parameter to the :func:`connect`
Georg Brandl116aa622007-08-15 14:28:22 +00001027call, or via the :attr:`isolation_level` property of connections.
Berker Peksaga71fed02018-07-29 12:01:38 +03001028If you specify no *isolation_level*, a plain ``BEGIN`` is used, which is
1029equivalent to specifying ``DEFERRED``. Other possible values are ``IMMEDIATE``
1030and ``EXCLUSIVE``.
Georg Brandl116aa622007-08-15 14:28:22 +00001031
Berker Peksaga71fed02018-07-29 12:01:38 +03001032You can disable the :mod:`sqlite3` module's implicit transaction management by
1033setting :attr:`isolation_level` to ``None``. This will leave the underlying
1034``sqlite3`` library operating in ``autocommit`` mode. You can then completely
1035control the transaction state by explicitly issuing ``BEGIN``, ``ROLLBACK``,
1036``SAVEPOINT``, and ``RELEASE`` statements in your code.
Berker Peksagfe70d922017-02-26 18:31:12 +03001037
Berker Peksagab994ed2016-09-11 12:57:15 +03001038.. versionchanged:: 3.6
1039 :mod:`sqlite3` used to implicitly commit an open transaction before DDL
1040 statements. This is no longer the case.
Georg Brandl116aa622007-08-15 14:28:22 +00001041
1042
Georg Brandl8a1e4c42009-05-25 21:13:36 +00001043Using :mod:`sqlite3` efficiently
1044--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001045
1046
1047Using shortcut methods
1048^^^^^^^^^^^^^^^^^^^^^^
1049
1050Using the nonstandard :meth:`execute`, :meth:`executemany` and
1051:meth:`executescript` methods of the :class:`Connection` object, your code can
1052be written more concisely because you don't have to create the (often
1053superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
1054objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001055objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +00001056directly using only a single call on the :class:`Connection` object.
1057
1058.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
1059
1060
1061Accessing columns by name instead of by index
1062^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1063
Georg Brandl22b34312009-07-26 14:54:51 +00001064One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +00001065:class:`sqlite3.Row` class designed to be used as a row factory.
1066
1067Rows wrapped with this class can be accessed both by index (like tuples) and
1068case-insensitively by name:
1069
1070.. literalinclude:: ../includes/sqlite3/rowclass.py
1071
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +00001072
1073Using the connection as a context manager
1074^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1075
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +00001076Connection objects can be used as context managers
1077that automatically commit or rollback transactions. In the event of an
1078exception, the transaction is rolled back; otherwise, the transaction is
1079committed:
1080
1081.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +00001082
1083
1084Common issues
1085-------------
1086
1087Multithreading
1088^^^^^^^^^^^^^^
1089
1090Older SQLite versions had issues with sharing connections between threads.
1091That's why the Python module disallows sharing connections and cursors between
1092threads. If you still try to do so, you will get an exception at runtime.
1093
1094The only exception is calling the :meth:`~Connection.interrupt` method, which
1095only makes sense to call from a different thread.
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
1102 extension support, you must pass --enable-loadable-sqlite-extensions to
1103 configure.