blob: ae4c7c49ccf201c15ed50e14fe5fcd1ec889d86e [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
Zachary Ware9d085622014-04-01 12:21:56 -0500110 http://www.w3schools.com/sql/
111 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
175 Opens a connection to the SQLite database file *database*. You can use
176 ``":memory:"`` to open a database connection to a database that resides in RAM
177 instead of on disk.
178
179 When a database is accessed by multiple connections, and one of the processes
180 modifies the database, the SQLite database is locked until that transaction is
181 committed. The *timeout* parameter specifies how long the connection should wait
182 for the lock to go away until raising an exception. The default for the timeout
183 parameter is 5.0 (five seconds).
184
185 For the *isolation_level* parameter, please see the
186 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
187
Georg Brandl3c127112013-10-06 12:38:44 +0200188 SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
Georg Brandl116aa622007-08-15 14:28:22 +0000189 you want to use other types you must add support for them yourself. The
190 *detect_types* parameter and the using custom **converters** registered with the
191 module-level :func:`register_converter` function allow you to easily do that.
192
193 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
194 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
195 type detection on.
196
Senthil Kumaran7ee91942016-06-03 00:03:48 -0700197 By default, *check_same_thread* is :const:`True` and only the creating thread may
198 use the connection. If set :const:`False`, the returned connection may be shared
199 across multiple threads. When using multiple threads with the same connection
200 writing operations should be serialized by the user to avoid data corruption.
201
Georg Brandl116aa622007-08-15 14:28:22 +0000202 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
203 connect call. You can, however, subclass the :class:`Connection` class and make
204 :func:`connect` use your class instead by providing your class for the *factory*
205 parameter.
206
207 Consult the section :ref:`sqlite3-types` of this manual for details.
208
209 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
210 overhead. If you want to explicitly set the number of statements that are cached
211 for the connection, you can set the *cached_statements* parameter. The currently
212 implemented default is to cache 100 statements.
213
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100214 If *uri* is true, *database* is interpreted as a URI. This allows you
215 to specify options. For example, to open a database in read-only mode
216 you can use::
217
218 db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)
219
220 More information about this feature, including a list of recognized options, can
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300221 be found in the `SQLite URI documentation <https://www.sqlite.org/uri.html>`_.
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100222
223 .. versionchanged:: 3.4
224 Added the *uri* parameter.
225
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227.. function:: register_converter(typename, callable)
228
229 Registers a callable to convert a bytestring from the database into a custom
230 Python type. The callable will be invoked for all database values that are of
231 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
232 function for how the type detection works. Note that the case of *typename* and
233 the name of the type in your query must match!
234
235
236.. function:: register_adapter(type, callable)
237
238 Registers a callable to convert the custom Python type *type* into one of
239 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000240 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000241 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243
244.. function:: complete_statement(sql)
245
246 Returns :const:`True` if the string *sql* contains one or more complete SQL
247 statements terminated by semicolons. It does not verify that the SQL is
248 syntactically correct, only that there are no unclosed string literals and the
249 statement is terminated by a semicolon.
250
251 This can be used to build a shell for SQLite, as in the following example:
252
253
254 .. literalinclude:: ../includes/sqlite3/complete_statement.py
255
256
257.. function:: enable_callback_tracebacks(flag)
258
259 By default you will not get any tracebacks in user-defined functions,
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200260 aggregates, converters, authorizer callbacks etc. If you want to debug them,
261 you can call this function with *flag* set to ``True``. Afterwards, you will
262 get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to
263 disable the feature again.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265
266.. _sqlite3-connection-objects:
267
268Connection Objects
269------------------
270
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000271.. class:: Connection
272
273 A SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000274
R David Murray6db23352012-09-30 20:44:43 -0400275 .. attribute:: isolation_level
Georg Brandl116aa622007-08-15 14:28:22 +0000276
R David Murray6db23352012-09-30 20:44:43 -0400277 Get or set the current isolation level. :const:`None` for autocommit mode or
278 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
279 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
R David Murray6db23352012-09-30 20:44:43 -0400281 .. attribute:: in_transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000282
R David Murray6db23352012-09-30 20:44:43 -0400283 :const:`True` if a transaction is active (there are uncommitted changes),
284 :const:`False` otherwise. Read-only attribute.
R. David Murrayd35251d2010-06-01 01:32:12 +0000285
R David Murray6db23352012-09-30 20:44:43 -0400286 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000287
R David Murray6db23352012-09-30 20:44:43 -0400288 .. method:: cursor([cursorClass])
Georg Brandl116aa622007-08-15 14:28:22 +0000289
R David Murray6db23352012-09-30 20:44:43 -0400290 The cursor method accepts a single optional parameter *cursorClass*. If
291 supplied, this must be a custom cursor class that extends
292 :class:`sqlite3.Cursor`.
Georg Brandl116aa622007-08-15 14:28:22 +0000293
R David Murray6db23352012-09-30 20:44:43 -0400294 .. method:: commit()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000295
R David Murray6db23352012-09-30 20:44:43 -0400296 This method commits the current transaction. If you don't call this method,
297 anything you did since the last call to ``commit()`` is not visible from
298 other database connections. If you wonder why you don't see the data you've
299 written to the database, please check you didn't forget to call this method.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000300
R David Murray6db23352012-09-30 20:44:43 -0400301 .. method:: rollback()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000302
R David Murray6db23352012-09-30 20:44:43 -0400303 This method rolls back any changes to the database since the last call to
304 :meth:`commit`.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000305
R David Murray6db23352012-09-30 20:44:43 -0400306 .. method:: close()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000307
R David Murray6db23352012-09-30 20:44:43 -0400308 This closes the database connection. Note that this does not automatically
309 call :meth:`commit`. If you just close your database connection without
310 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000311
Berker Peksagc4154402016-06-12 13:41:47 +0300312 .. method:: execute(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Berker Peksagc4154402016-06-12 13:41:47 +0300314 This is a nonstandard shortcut that creates a cursor object by calling
315 the :meth:`~Connection.cursor` method, calls the cursor's
316 :meth:`~Cursor.execute` method with the *parameters* given, and returns
317 the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000318
Berker Peksagc4154402016-06-12 13:41:47 +0300319 .. method:: executemany(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
322 calling the :meth:`~Connection.cursor` method, calls the cursor's
323 :meth:`~Cursor.executemany` method with the *parameters* given, and
324 returns the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000325
R David Murray6db23352012-09-30 20:44:43 -0400326 .. method:: executescript(sql_script)
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.executescript` method with the given *sql_script*, and
331 returns the cursor.
Georg Brandl116aa622007-08-15 14:28:22 +0000332
R David Murray6db23352012-09-30 20:44:43 -0400333 .. method:: create_function(name, num_params, func)
Georg Brandl116aa622007-08-15 14:28:22 +0000334
R David Murray6db23352012-09-30 20:44:43 -0400335 Creates a user-defined function that you can later use from within SQL
336 statements under the function name *name*. *num_params* is the number of
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300337 parameters the function accepts (if *num_params* is -1, the function may
338 take any number of arguments), and *func* is a Python callable that is
339 called as the SQL function.
Georg Brandl116aa622007-08-15 14:28:22 +0000340
R David Murray6db23352012-09-30 20:44:43 -0400341 The function can return any of the types supported by SQLite: bytes, str, int,
342 float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
R David Murray6db23352012-09-30 20:44:43 -0400344 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000345
R David Murray6db23352012-09-30 20:44:43 -0400346 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348
R David Murray6db23352012-09-30 20:44:43 -0400349 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl116aa622007-08-15 14:28:22 +0000350
R David Murray6db23352012-09-30 20:44:43 -0400351 Creates a user-defined aggregate function.
Georg Brandl116aa622007-08-15 14:28:22 +0000352
R David Murray6db23352012-09-30 20:44:43 -0400353 The aggregate class must implement a ``step`` method, which accepts the number
Berker Peksagfa0f62d2016-03-27 22:39:14 +0300354 of parameters *num_params* (if *num_params* is -1, the function may take
355 any number of arguments), and a ``finalize`` method which will return the
R David Murray6db23352012-09-30 20:44:43 -0400356 final result of the aggregate.
Georg Brandl116aa622007-08-15 14:28:22 +0000357
R David Murray6db23352012-09-30 20:44:43 -0400358 The ``finalize`` method can return any of the types supported by SQLite:
359 bytes, str, int, float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
R David Murray6db23352012-09-30 20:44:43 -0400361 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000362
R David Murray6db23352012-09-30 20:44:43 -0400363 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365
R David Murray6db23352012-09-30 20:44:43 -0400366 .. method:: create_collation(name, callable)
Georg Brandl116aa622007-08-15 14:28:22 +0000367
R David Murray6db23352012-09-30 20:44:43 -0400368 Creates a collation with the specified *name* and *callable*. The callable will
369 be passed two string arguments. It should return -1 if the first is ordered
370 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
371 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
372 your comparisons don't affect other SQL operations.
Georg Brandl116aa622007-08-15 14:28:22 +0000373
R David Murray6db23352012-09-30 20:44:43 -0400374 Note that the callable will get its parameters as Python bytestrings, which will
375 normally be encoded in UTF-8.
Georg Brandl116aa622007-08-15 14:28:22 +0000376
R David Murray6db23352012-09-30 20:44:43 -0400377 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl116aa622007-08-15 14:28:22 +0000378
R David Murray6db23352012-09-30 20:44:43 -0400379 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl116aa622007-08-15 14:28:22 +0000380
R David Murray6db23352012-09-30 20:44:43 -0400381 To remove a collation, call ``create_collation`` with None as callable::
Georg Brandl116aa622007-08-15 14:28:22 +0000382
R David Murray6db23352012-09-30 20:44:43 -0400383 con.create_collation("reverse", None)
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385
R David Murray6db23352012-09-30 20:44:43 -0400386 .. method:: interrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000387
R David Murray6db23352012-09-30 20:44:43 -0400388 You can call this method from a different thread to abort any queries that might
389 be executing on the connection. The query will then abort and the caller will
390 get an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000391
392
R David Murray6db23352012-09-30 20:44:43 -0400393 .. method:: set_authorizer(authorizer_callback)
Georg Brandl116aa622007-08-15 14:28:22 +0000394
R David Murray6db23352012-09-30 20:44:43 -0400395 This routine registers a callback. The callback is invoked for each attempt to
396 access a column of a table in the database. The callback should return
397 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
398 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
399 column should be treated as a NULL value. These constants are available in the
400 :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000401
R David Murray6db23352012-09-30 20:44:43 -0400402 The first argument to the callback signifies what kind of operation is to be
403 authorized. The second and third argument will be arguments or :const:`None`
404 depending on the first argument. The 4th argument is the name of the database
405 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
406 inner-most trigger or view that is responsible for the access attempt or
407 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl116aa622007-08-15 14:28:22 +0000408
R David Murray6db23352012-09-30 20:44:43 -0400409 Please consult the SQLite documentation about the possible values for the first
410 argument and the meaning of the second and third argument depending on the first
411 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000412
Georg Brandl116aa622007-08-15 14:28:22 +0000413
R David Murray6db23352012-09-30 20:44:43 -0400414 .. method:: set_progress_handler(handler, n)
Georg Brandl116aa622007-08-15 14:28:22 +0000415
R David Murray6db23352012-09-30 20:44:43 -0400416 This routine registers a callback. The callback is invoked for every *n*
417 instructions of the SQLite virtual machine. This is useful if you want to
418 get called from SQLite during long-running operations, for example to update
419 a GUI.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000420
R David Murray6db23352012-09-30 20:44:43 -0400421 If you want to clear any previously installed progress handler, call the
422 method with :const:`None` for *handler*.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000423
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000424
R David Murray842ca5f2012-09-30 20:49:19 -0400425 .. method:: set_trace_callback(trace_callback)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000426
R David Murray842ca5f2012-09-30 20:49:19 -0400427 Registers *trace_callback* to be called for each SQL statement that is
428 actually executed by the SQLite backend.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200429
R David Murray842ca5f2012-09-30 20:49:19 -0400430 The only argument passed to the callback is the statement (as string) that
431 is being executed. The return value of the callback is ignored. Note that
432 the backend does not only run statements passed to the :meth:`Cursor.execute`
433 methods. Other sources include the transaction management of the Python
434 module and the execution of triggers defined in the current database.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200435
R David Murray842ca5f2012-09-30 20:49:19 -0400436 Passing :const:`None` as *trace_callback* will disable the trace callback.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200437
R David Murray842ca5f2012-09-30 20:49:19 -0400438 .. versionadded:: 3.3
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200439
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200440
R David Murray6db23352012-09-30 20:44:43 -0400441 .. method:: enable_load_extension(enabled)
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200442
R David Murray6db23352012-09-30 20:44:43 -0400443 This routine allows/disallows the SQLite engine to load SQLite extensions
444 from shared libraries. SQLite extensions can define new functions,
445 aggregates or whole new virtual table implementations. One well-known
446 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000447
R David Murray6db23352012-09-30 20:44:43 -0400448 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000449
R David Murray6db23352012-09-30 20:44:43 -0400450 .. versionadded:: 3.2
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200451
R David Murray6db23352012-09-30 20:44:43 -0400452 .. literalinclude:: ../includes/sqlite3/load_extension.py
Georg Brandl67b21b72010-08-17 15:07:14 +0000453
R David Murray6db23352012-09-30 20:44:43 -0400454 .. method:: load_extension(path)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000455
R David Murray6db23352012-09-30 20:44:43 -0400456 This routine loads a SQLite extension from a shared library. You have to
457 enable extension loading with :meth:`enable_load_extension` before you can
458 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000459
R David Murray6db23352012-09-30 20:44:43 -0400460 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000461
R David Murray6db23352012-09-30 20:44:43 -0400462 .. versionadded:: 3.2
Gerhard Häringe0941c52010-10-03 21:47:06 +0000463
R David Murray6db23352012-09-30 20:44:43 -0400464 .. attribute:: row_factory
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200465
R David Murray6db23352012-09-30 20:44:43 -0400466 You can change this attribute to a callable that accepts the cursor and the
467 original row as a tuple and will return the real result row. This way, you can
468 implement more advanced ways of returning results, such as returning an object
469 that can also access columns by name.
Georg Brandl116aa622007-08-15 14:28:22 +0000470
R David Murray6db23352012-09-30 20:44:43 -0400471 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000472
R David Murray6db23352012-09-30 20:44:43 -0400473 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000474
R David Murray6db23352012-09-30 20:44:43 -0400475 If returning a tuple doesn't suffice and you want name-based access to
476 columns, you should consider setting :attr:`row_factory` to the
477 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
478 index-based and case-insensitive name-based access to columns with almost no
479 memory overhead. It will probably be better than your own custom
480 dictionary-based approach or even a db_row based solution.
Georg Brandl116aa622007-08-15 14:28:22 +0000481
R David Murray6db23352012-09-30 20:44:43 -0400482 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000483
Georg Brandl116aa622007-08-15 14:28:22 +0000484
R David Murray6db23352012-09-30 20:44:43 -0400485 .. attribute:: text_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000486
R David Murray6db23352012-09-30 20:44:43 -0400487 Using this attribute you can control what objects are returned for the ``TEXT``
488 data type. By default, this attribute is set to :class:`str` and the
489 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
490 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000491
R David Murray6db23352012-09-30 20:44:43 -0400492 For efficiency reasons, there's also a way to return :class:`str` objects
493 only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
494 this attribute to :const:`sqlite3.OptimizedUnicode`.
Georg Brandl116aa622007-08-15 14:28:22 +0000495
R David Murray6db23352012-09-30 20:44:43 -0400496 You can also set it to any other callable that accepts a single bytestring
497 parameter and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000498
R David Murray6db23352012-09-30 20:44:43 -0400499 See the following example code for illustration:
Georg Brandl116aa622007-08-15 14:28:22 +0000500
R David Murray6db23352012-09-30 20:44:43 -0400501 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000502
503
R David Murray6db23352012-09-30 20:44:43 -0400504 .. attribute:: total_changes
Georg Brandl116aa622007-08-15 14:28:22 +0000505
R David Murray6db23352012-09-30 20:44:43 -0400506 Returns the total number of database rows that have been modified, inserted, or
507 deleted since the database connection was opened.
Georg Brandl116aa622007-08-15 14:28:22 +0000508
509
Berker Peksag557a0632016-03-27 18:46:18 +0300510 .. method:: iterdump
Christian Heimesbbe741d2008-03-28 10:53:29 +0000511
R David Murray6db23352012-09-30 20:44:43 -0400512 Returns an iterator to dump the database in an SQL text format. Useful when
513 saving an in-memory database for later restoration. This function provides
514 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
515 shell.
Christian Heimesbbe741d2008-03-28 10:53:29 +0000516
R David Murray6db23352012-09-30 20:44:43 -0400517 Example::
Christian Heimesbbe741d2008-03-28 10:53:29 +0000518
R David Murray6db23352012-09-30 20:44:43 -0400519 # Convert file existing_db.db to SQL dump file dump.sql
Berker Peksag557a0632016-03-27 18:46:18 +0300520 import sqlite3
Christian Heimesbbe741d2008-03-28 10:53:29 +0000521
R David Murray6db23352012-09-30 20:44:43 -0400522 con = sqlite3.connect('existing_db.db')
523 with open('dump.sql', 'w') as f:
524 for line in con.iterdump():
525 f.write('%s\n' % line)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000526
527
Georg Brandl116aa622007-08-15 14:28:22 +0000528.. _sqlite3-cursor-objects:
529
530Cursor Objects
531--------------
532
Georg Brandl96115fb22010-10-17 09:33:24 +0000533.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000534
Georg Brandl96115fb22010-10-17 09:33:24 +0000535 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000536
Berker Peksagc4154402016-06-12 13:41:47 +0300537 .. method:: execute(sql[, parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000538
Zachary Ware9d085622014-04-01 12:21:56 -0500539 Executes an SQL statement. The SQL statement may be parameterized (i. e.
R David Murray6db23352012-09-30 20:44:43 -0400540 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
541 kinds of placeholders: question marks (qmark style) and named placeholders
542 (named style).
Georg Brandl116aa622007-08-15 14:28:22 +0000543
R David Murray6db23352012-09-30 20:44:43 -0400544 Here's an example of both styles:
Georg Brandl116aa622007-08-15 14:28:22 +0000545
R David Murray6db23352012-09-30 20:44:43 -0400546 .. literalinclude:: ../includes/sqlite3/execute_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000547
R David Murray6db23352012-09-30 20:44:43 -0400548 :meth:`execute` will only execute a single SQL statement. If you try to execute
Berker Peksagc4154402016-06-12 13:41:47 +0300549 more than one statement with it, it will raise an ``sqlite3.Warning``. Use
R David Murray6db23352012-09-30 20:44:43 -0400550 :meth:`executescript` if you want to execute multiple SQL statements with one
551 call.
Georg Brandl116aa622007-08-15 14:28:22 +0000552
553
R David Murray6db23352012-09-30 20:44:43 -0400554 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl116aa622007-08-15 14:28:22 +0000555
R David Murray6db23352012-09-30 20:44:43 -0400556 Executes an SQL command against all parameter sequences or mappings found in
Berker Peksagc4154402016-06-12 13:41:47 +0300557 the sequence *seq_of_parameters*. The :mod:`sqlite3` module also allows
558 using an :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000559
R David Murray6db23352012-09-30 20:44:43 -0400560 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000561
R David Murray6db23352012-09-30 20:44:43 -0400562 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000563
R David Murray6db23352012-09-30 20:44:43 -0400564 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl116aa622007-08-15 14:28:22 +0000565
566
R David Murray6db23352012-09-30 20:44:43 -0400567 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000568
R David Murray6db23352012-09-30 20:44:43 -0400569 This is a nonstandard convenience method for executing multiple SQL statements
570 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
571 gets as a parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000572
Berker Peksagc4154402016-06-12 13:41:47 +0300573 *sql_script* can be an instance of :class:`str`.
Georg Brandl116aa622007-08-15 14:28:22 +0000574
R David Murray6db23352012-09-30 20:44:43 -0400575 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000576
R David Murray6db23352012-09-30 20:44:43 -0400577 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl116aa622007-08-15 14:28:22 +0000578
579
R David Murray6db23352012-09-30 20:44:43 -0400580 .. method:: fetchone()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000581
R David Murray6db23352012-09-30 20:44:43 -0400582 Fetches the next row of a query result set, returning a single sequence,
583 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000584
585
R David Murray6db23352012-09-30 20:44:43 -0400586 .. method:: fetchmany(size=cursor.arraysize)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000587
R David Murray6db23352012-09-30 20:44:43 -0400588 Fetches the next set of rows of a query result, returning a list. An empty
589 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000590
R David Murray6db23352012-09-30 20:44:43 -0400591 The number of rows to fetch per call is specified by the *size* parameter.
592 If it is not given, the cursor's arraysize determines the number of rows
593 to be fetched. The method should try to fetch as many rows as indicated by
594 the size parameter. If this is not possible due to the specified number of
595 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000596
R David Murray6db23352012-09-30 20:44:43 -0400597 Note there are performance considerations involved with the *size* parameter.
598 For optimal performance, it is usually best to use the arraysize attribute.
599 If the *size* parameter is used, then it is best for it to retain the same
600 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000601
R David Murray6db23352012-09-30 20:44:43 -0400602 .. method:: fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000603
R David Murray6db23352012-09-30 20:44:43 -0400604 Fetches all (remaining) rows of a query result, returning a list. Note that
605 the cursor's arraysize attribute can affect the performance of this operation.
606 An empty list is returned when no rows are available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000607
Berker Peksagf70fe6f2016-03-27 21:51:02 +0300608 .. method:: close()
609
610 Close the cursor now (rather than whenever ``__del__`` is called).
611
612 The cursor will be unusable from this point forward; a ``ProgrammingError``
613 exception will be raised if any operation is attempted with the cursor.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000614
R David Murray6db23352012-09-30 20:44:43 -0400615 .. attribute:: rowcount
Georg Brandl116aa622007-08-15 14:28:22 +0000616
R David Murray6db23352012-09-30 20:44:43 -0400617 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
618 attribute, the database engine's own support for the determination of "rows
619 affected"/"rows selected" is quirky.
Georg Brandl116aa622007-08-15 14:28:22 +0000620
R David Murray6db23352012-09-30 20:44:43 -0400621 For :meth:`executemany` statements, the number of modifications are summed up
622 into :attr:`rowcount`.
Georg Brandl116aa622007-08-15 14:28:22 +0000623
R David Murray6db23352012-09-30 20:44:43 -0400624 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
625 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
626 last operation is not determinable by the interface". This includes ``SELECT``
627 statements because we cannot determine the number of rows a query produced
628 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000629
R David Murray6db23352012-09-30 20:44:43 -0400630 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
631 you make a ``DELETE FROM table`` without any condition.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000632
R David Murray6db23352012-09-30 20:44:43 -0400633 .. attribute:: lastrowid
Gerhard Häringd3372792008-03-29 19:13:55 +0000634
R David Murray6db23352012-09-30 20:44:43 -0400635 This read-only attribute provides the rowid of the last modified row. It is
Martin Panter7462b6492015-11-02 03:37:02 +0000636 only set if you issued an ``INSERT`` statement using the :meth:`execute`
R David Murray6db23352012-09-30 20:44:43 -0400637 method. For operations other than ``INSERT`` or when :meth:`executemany` is
638 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl116aa622007-08-15 14:28:22 +0000639
R David Murray6db23352012-09-30 20:44:43 -0400640 .. attribute:: description
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000641
R David Murray6db23352012-09-30 20:44:43 -0400642 This read-only attribute provides the column names of the last query. To
643 remain compatible with the Python DB API, it returns a 7-tuple for each
644 column where the last six items of each tuple are :const:`None`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000645
R David Murray6db23352012-09-30 20:44:43 -0400646 It is set for ``SELECT`` statements without any matching rows as well.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000647
Ezio Melotti62564db2016-03-18 20:10:36 +0200648 .. attribute:: connection
649
650 This read-only attribute provides the SQLite database :class:`Connection`
651 used by the :class:`Cursor` object. A :class:`Cursor` object created by
652 calling :meth:`con.cursor() <Connection.cursor>` will have a
653 :attr:`connection` attribute that refers to *con*::
654
655 >>> con = sqlite3.connect(":memory:")
656 >>> cur = con.cursor()
657 >>> cur.connection == con
658 True
659
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000660.. _sqlite3-row-objects:
661
662Row Objects
663-----------
664
665.. class:: Row
666
667 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000668 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000669 It tries to mimic a tuple in most of its features.
670
671 It supports mapping access by column name and index, iteration,
672 representation, equality testing and :func:`len`.
673
674 If two :class:`Row` objects have exactly the same columns and their
675 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000676
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000677 .. method:: keys
678
R David Murray092135e2014-06-05 15:16:38 -0400679 This method returns a list of column names. Immediately after a query,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000680 it is the first member of each tuple in :attr:`Cursor.description`.
681
Serhiy Storchaka72e731c2015-03-31 13:33:11 +0300682 .. versionchanged:: 3.5
683 Added support of slicing.
684
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000685Let's assume we initialize a table as in the example given above::
686
Senthil Kumaran946eb862011-07-03 10:17:22 -0700687 conn = sqlite3.connect(":memory:")
688 c = conn.cursor()
689 c.execute('''create table stocks
690 (date text, trans text, symbol text,
691 qty real, price real)''')
692 c.execute("""insert into stocks
693 values ('2006-01-05','BUY','RHAT',100,35.14)""")
694 conn.commit()
695 c.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000696
697Now we plug :class:`Row` in::
698
Senthil Kumaran946eb862011-07-03 10:17:22 -0700699 >>> conn.row_factory = sqlite3.Row
700 >>> c = conn.cursor()
701 >>> c.execute('select * from stocks')
702 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
703 >>> r = c.fetchone()
704 >>> type(r)
705 <class 'sqlite3.Row'>
706 >>> tuple(r)
707 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
708 >>> len(r)
709 5
710 >>> r[2]
711 'RHAT'
712 >>> r.keys()
713 ['date', 'trans', 'symbol', 'qty', 'price']
714 >>> r['qty']
715 100.0
716 >>> for member in r:
717 ... print(member)
718 ...
719 2006-01-05
720 BUY
721 RHAT
722 100.0
723 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000724
725
Georg Brandl116aa622007-08-15 14:28:22 +0000726.. _sqlite3-types:
727
728SQLite and Python types
729-----------------------
730
731
732Introduction
733^^^^^^^^^^^^
734
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000735SQLite natively supports the following types: ``NULL``, ``INTEGER``,
736``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000737
738The following Python types can thus be sent to SQLite without any problem:
739
Georg Brandlf6945182008-02-01 11:56:49 +0000740+-------------------------------+-------------+
741| Python type | SQLite type |
742+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000743| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000744+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000745| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000746+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000747| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000748+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000749| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000750+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000751| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000752+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000753
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000754
Georg Brandl116aa622007-08-15 14:28:22 +0000755This is how SQLite types are converted to Python types by default:
756
Zachary Ware9d085622014-04-01 12:21:56 -0500757+-------------+----------------------------------------------+
758| SQLite type | Python type |
759+=============+==============================================+
760| ``NULL`` | :const:`None` |
761+-------------+----------------------------------------------+
762| ``INTEGER`` | :class:`int` |
763+-------------+----------------------------------------------+
764| ``REAL`` | :class:`float` |
765+-------------+----------------------------------------------+
766| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
767| | :class:`str` by default |
768+-------------+----------------------------------------------+
769| ``BLOB`` | :class:`bytes` |
770+-------------+----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000771
772The type system of the :mod:`sqlite3` module is extensible in two ways: you can
773store additional Python types in a SQLite database via object adaptation, and
774you can let the :mod:`sqlite3` module convert SQLite types to different Python
775types via converters.
776
777
778Using adapters to store additional Python types in SQLite databases
779^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
780
781As described before, SQLite supports only a limited set of types natively. To
782use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000783sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000784str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Georg Brandl116aa622007-08-15 14:28:22 +0000786There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
787type to one of the supported ones.
788
789
790Letting your object adapt itself
791""""""""""""""""""""""""""""""""
792
793This is a good approach if you write the class yourself. Let's suppose you have
794a class like this::
795
Éric Araujo28053fb2010-11-22 03:09:19 +0000796 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000797 def __init__(self, x, y):
798 self.x, self.y = x, y
799
800Now you want to store the point in a single SQLite column. First you'll have to
801choose one of the supported types first to be used for representing the point.
802Let's just use str and separate the coordinates using a semicolon. Then you need
803to give your class a method ``__conform__(self, protocol)`` which must return
804the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
805
806.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
807
808
809Registering an adapter callable
810"""""""""""""""""""""""""""""""
811
812The other possibility is to create a function that converts the type to the
813string representation and register the function with :meth:`register_adapter`.
814
Georg Brandl116aa622007-08-15 14:28:22 +0000815.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
816
817The :mod:`sqlite3` module has two default adapters for Python's built-in
818:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
819we want to store :class:`datetime.datetime` objects not in ISO representation,
820but as a Unix timestamp.
821
822.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
823
824
825Converting SQLite values to custom Python types
826^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
827
828Writing an adapter lets you send custom Python types to SQLite. But to make it
829really useful we need to make the Python to SQLite to Python roundtrip work.
830
831Enter converters.
832
833Let's go back to the :class:`Point` class. We stored the x and y coordinates
834separated via semicolons as strings in SQLite.
835
836First, we'll define a converter function that accepts the string as a parameter
837and constructs a :class:`Point` object from it.
838
839.. note::
840
Zachary Ware9d085622014-04-01 12:21:56 -0500841 Converter functions **always** get called with a :class:`bytes` object, no
842 matter under which data type you sent the value to SQLite.
Georg Brandl116aa622007-08-15 14:28:22 +0000843
Georg Brandl116aa622007-08-15 14:28:22 +0000844::
845
846 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200847 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +0000848 return Point(x, y)
849
850Now you need to make the :mod:`sqlite3` module know that what you select from
851the database is actually a point. There are two ways of doing this:
852
853* Implicitly via the declared type
854
855* Explicitly via the column name
856
857Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
858for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
859
860The following example illustrates both approaches.
861
862.. literalinclude:: ../includes/sqlite3/converter_point.py
863
864
865Default adapters and converters
866^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
867
868There are default adapters for the date and datetime types in the datetime
869module. They will be sent as ISO dates/ISO timestamps to SQLite.
870
871The default converters are registered under the name "date" for
872:class:`datetime.date` and under the name "timestamp" for
873:class:`datetime.datetime`.
874
875This way, you can use date/timestamps from Python without any additional
876fiddling in most cases. The format of the adapters is also compatible with the
877experimental SQLite date/time functions.
878
879The following example demonstrates this.
880
881.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
882
Petri Lehtinen5f794092013-02-26 21:32:02 +0200883If a timestamp stored in SQLite has a fractional part longer than 6
884numbers, its value will be truncated to microsecond precision by the
885timestamp converter.
886
Georg Brandl116aa622007-08-15 14:28:22 +0000887
888.. _sqlite3-controlling-transactions:
889
890Controlling Transactions
891------------------------
892
893By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandl48310cd2009-01-03 21:18:54 +0000894Data Modification Language (DML) statement (i.e.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000895``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
896implicitly before a non-DML, non-query statement (i. e.
897anything other than ``SELECT`` or the aforementioned).
Georg Brandl116aa622007-08-15 14:28:22 +0000898
899So if you are within a transaction and issue a command like ``CREATE TABLE
900...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
901before executing that command. There are two reasons for doing that. The first
902is that some of these commands don't work within transactions. The other reason
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000903is that sqlite3 needs to keep track of the transaction state (if a transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000904is active or not). The current transaction state is exposed through the
905:attr:`Connection.in_transaction` attribute of the connection object.
Georg Brandl116aa622007-08-15 14:28:22 +0000906
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000907You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl116aa622007-08-15 14:28:22 +0000908(or none at all) via the *isolation_level* parameter to the :func:`connect`
909call, or via the :attr:`isolation_level` property of connections.
910
911If you want **autocommit mode**, then set :attr:`isolation_level` to None.
912
913Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandla971c652008-11-07 09:39:56 +0000914statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
915"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl116aa622007-08-15 14:28:22 +0000916
Georg Brandl116aa622007-08-15 14:28:22 +0000917
918
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000919Using :mod:`sqlite3` efficiently
920--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000921
922
923Using shortcut methods
924^^^^^^^^^^^^^^^^^^^^^^
925
926Using the nonstandard :meth:`execute`, :meth:`executemany` and
927:meth:`executescript` methods of the :class:`Connection` object, your code can
928be written more concisely because you don't have to create the (often
929superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
930objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000931objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +0000932directly using only a single call on the :class:`Connection` object.
933
934.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
935
936
937Accessing columns by name instead of by index
938^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
939
Georg Brandl22b34312009-07-26 14:54:51 +0000940One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000941:class:`sqlite3.Row` class designed to be used as a row factory.
942
943Rows wrapped with this class can be accessed both by index (like tuples) and
944case-insensitively by name:
945
946.. literalinclude:: ../includes/sqlite3/rowclass.py
947
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000948
949Using the connection as a context manager
950^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
951
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000952Connection objects can be used as context managers
953that automatically commit or rollback transactions. In the event of an
954exception, the transaction is rolled back; otherwise, the transaction is
955committed:
956
957.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +0000958
959
960Common issues
961-------------
962
963Multithreading
964^^^^^^^^^^^^^^
965
966Older SQLite versions had issues with sharing connections between threads.
967That's why the Python module disallows sharing connections and cursors between
968threads. If you still try to do so, you will get an exception at runtime.
969
970The only exception is calling the :meth:`~Connection.interrupt` method, which
971only makes sense to call from a different thread.
972
Gerhard Häringe0941c52010-10-03 21:47:06 +0000973.. rubric:: Footnotes
974
975.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumaran946eb862011-07-03 10:17:22 -0700976 default, because some platforms (notably Mac OS X) have SQLite
977 libraries which are compiled without this feature. To get loadable
978 extension support, you must pass --enable-loadable-sqlite-extensions to
979 configure.