blob: 7d156def455538ff3dba1d347bf0796741e823ba [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.
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +02006.. sectionauthor:: Gerhard Häring <gh@ghaering.de>
Georg Brandl116aa622007-08-15 14:28:22 +00007
8
Georg Brandl116aa622007-08-15 14:28:22 +00009SQLite is a C library that provides a lightweight disk-based database that
10doesn't require a separate server process and allows accessing the database
11using a nonstandard variant of the SQL query language. Some applications can use
12SQLite for internal data storage. It's also possible to prototype an
13application using SQLite and then port the code to a larger database such as
14PostgreSQL or Oracle.
15
Georg Brandl8a1e4c42009-05-25 21:13:36 +000016sqlite3 was written by Gerhard Häring and provides a SQL interface compliant
Georg Brandl116aa622007-08-15 14:28:22 +000017with the DB-API 2.0 specification described by :pep:`249`.
18
19To use the module, you must first create a :class:`Connection` object that
20represents the database. Here the data will be stored in the
21:file:`/tmp/example` file::
22
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020023 import sqlite3
Georg Brandl116aa622007-08-15 14:28:22 +000024 conn = sqlite3.connect('/tmp/example')
25
26You can also supply the special name ``:memory:`` to create a database in RAM.
27
28Once you have a :class:`Connection`, you can create a :class:`Cursor` object
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000029and call its :meth:`~Cursor.execute` method to perform SQL commands::
Georg Brandl116aa622007-08-15 14:28:22 +000030
31 c = conn.cursor()
32
33 # Create table
34 c.execute('''create table stocks
35 (date text, trans text, symbol text,
36 qty real, price real)''')
37
38 # Insert a row of data
39 c.execute("""insert into stocks
40 values ('2006-01-05','BUY','RHAT',100,35.14)""")
41
42 # Save (commit) the changes
43 conn.commit()
44
45 # We can also close the cursor if we are done with it
46 c.close()
47
48Usually your SQL operations will need to use values from Python variables. You
49shouldn't assemble your query using Python's string operations because doing so
50is insecure; it makes your program vulnerable to an SQL injection attack.
51
52Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
53wherever you want to use a value, and then provide a tuple of values as the
Georg Brandl8a1e4c42009-05-25 21:13:36 +000054second argument to the cursor's :meth:`~Cursor.execute` method. (Other database
55modules may use a different placeholder, such as ``%s`` or ``:1``.) For
56example::
Georg Brandl116aa622007-08-15 14:28:22 +000057
58 # Never do this -- insecure!
59 symbol = 'IBM'
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020060 c.execute("select * from stocks where symbol = '%s'" % symbol)
Georg Brandl116aa622007-08-15 14:28:22 +000061
62 # Do this instead
R David Murrayf6bd1b02012-08-20 14:14:18 -040063 t = ('IBM',)
Georg Brandl116aa622007-08-15 14:28:22 +000064 c.execute('select * from stocks where symbol=?', t)
65
66 # Larger example
Georg Brandla971c652008-11-07 09:39:56 +000067 for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020068 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
Georg Brandl116aa622007-08-15 14:28:22 +000069 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
Georg Brandla971c652008-11-07 09:39:56 +000070 ]:
Georg Brandl116aa622007-08-15 14:28:22 +000071 c.execute('insert into stocks values (?,?,?,?,?)', t)
72
Georg Brandl9afde1c2007-11-01 20:32:30 +000073To retrieve data after executing a SELECT statement, you can either treat the
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000074cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
75retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandl9afde1c2007-11-01 20:32:30 +000076matching rows.
Georg Brandl116aa622007-08-15 14:28:22 +000077
78This example uses the iterator form::
79
80 >>> c = conn.cursor()
81 >>> c.execute('select * from stocks order by price')
82 >>> for row in c:
Ezio Melottib5845052009-09-13 05:49:25 +000083 ... print(row)
Georg Brandl116aa622007-08-15 14:28:22 +000084 ...
Ezio Melottib5845052009-09-13 05:49:25 +000085 ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
86 ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
87 ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
88 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.0)
Georg Brandl116aa622007-08-15 14:28:22 +000089 >>>
90
91
92.. seealso::
93
Benjamin Peterson2614cda2010-03-21 22:36:19 +000094 http://code.google.com/p/pysqlite/
Georg Brandl8a1e4c42009-05-25 21:13:36 +000095 The pysqlite web page -- sqlite3 is developed externally under the name
96 "pysqlite".
Georg Brandl116aa622007-08-15 14:28:22 +000097
98 http://www.sqlite.org
Georg Brandl8a1e4c42009-05-25 21:13:36 +000099 The SQLite web page; the documentation describes the syntax and the
100 available data types for the supported SQL dialect.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102 :pep:`249` - Database API Specification 2.0
103 PEP written by Marc-André Lemburg.
104
105
106.. _sqlite3-module-contents:
107
108Module functions and constants
109------------------------------
110
111
112.. data:: PARSE_DECLTYPES
113
114 This constant is meant to be used with the *detect_types* parameter of the
115 :func:`connect` function.
116
117 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000118 column it returns. It will parse out the first word of the declared type,
119 i. e. for "integer primary key", it will parse out "integer", or for
120 "number(10)" it will parse out "number". Then for that column, it will look
121 into the converters dictionary and use the converter function registered for
122 that type there.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124
125.. data:: PARSE_COLNAMES
126
127 This constant is meant to be used with the *detect_types* parameter of the
128 :func:`connect` function.
129
130 Setting this makes the SQLite interface parse the column name for each column it
131 returns. It will look for a string formed [mytype] in there, and then decide
132 that 'mytype' is the type of the column. It will try to find an entry of
133 'mytype' in the converters dictionary and then use the converter function found
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000134 there to return the value. The column name found in :attr:`Cursor.description`
Georg Brandl116aa622007-08-15 14:28:22 +0000135 is only the first word of the column name, i. e. if you use something like
136 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
137 first blank for the column name: the column name would simply be "x".
138
139
Georg Brandl1c616a52010-07-10 12:01:34 +0000140.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
Georg Brandl116aa622007-08-15 14:28:22 +0000141
142 Opens a connection to the SQLite database file *database*. You can use
143 ``":memory:"`` to open a database connection to a database that resides in RAM
144 instead of on disk.
145
146 When a database is accessed by multiple connections, and one of the processes
147 modifies the database, the SQLite database is locked until that transaction is
148 committed. The *timeout* parameter specifies how long the connection should wait
149 for the lock to go away until raising an exception. The default for the timeout
150 parameter is 5.0 (five seconds).
151
152 For the *isolation_level* parameter, please see the
153 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
154
155 SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
156 you want to use other types you must add support for them yourself. The
157 *detect_types* parameter and the using custom **converters** registered with the
158 module-level :func:`register_converter` function allow you to easily do that.
159
160 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
161 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
162 type detection on.
163
164 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
165 connect call. You can, however, subclass the :class:`Connection` class and make
166 :func:`connect` use your class instead by providing your class for the *factory*
167 parameter.
168
169 Consult the section :ref:`sqlite3-types` of this manual for details.
170
171 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
172 overhead. If you want to explicitly set the number of statements that are cached
173 for the connection, you can set the *cached_statements* parameter. The currently
174 implemented default is to cache 100 statements.
175
176
177.. function:: register_converter(typename, callable)
178
179 Registers a callable to convert a bytestring from the database into a custom
180 Python type. The callable will be invoked for all database values that are of
181 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
182 function for how the type detection works. Note that the case of *typename* and
183 the name of the type in your query must match!
184
185
186.. function:: register_adapter(type, callable)
187
188 Registers a callable to convert the custom Python type *type* into one of
189 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000190 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000191 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193
194.. function:: complete_statement(sql)
195
196 Returns :const:`True` if the string *sql* contains one or more complete SQL
197 statements terminated by semicolons. It does not verify that the SQL is
198 syntactically correct, only that there are no unclosed string literals and the
199 statement is terminated by a semicolon.
200
201 This can be used to build a shell for SQLite, as in the following example:
202
203
204 .. literalinclude:: ../includes/sqlite3/complete_statement.py
205
206
207.. function:: enable_callback_tracebacks(flag)
208
209 By default you will not get any tracebacks in user-defined functions,
210 aggregates, converters, authorizer callbacks etc. If you want to debug them, you
211 can call this function with *flag* as True. Afterwards, you will get tracebacks
212 from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
213 again.
214
215
216.. _sqlite3-connection-objects:
217
218Connection Objects
219------------------
220
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000221.. class:: Connection
222
223 A SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000224
R David Murray6db23352012-09-30 20:44:43 -0400225 .. attribute:: isolation_level
Georg Brandl116aa622007-08-15 14:28:22 +0000226
R David Murray6db23352012-09-30 20:44:43 -0400227 Get or set the current isolation level. :const:`None` for autocommit mode or
228 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
229 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000230
R David Murray6db23352012-09-30 20:44:43 -0400231 .. attribute:: in_transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000232
R David Murray6db23352012-09-30 20:44:43 -0400233 :const:`True` if a transaction is active (there are uncommitted changes),
234 :const:`False` otherwise. Read-only attribute.
R. David Murrayd35251d2010-06-01 01:32:12 +0000235
R David Murray6db23352012-09-30 20:44:43 -0400236 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000237
R David Murray6db23352012-09-30 20:44:43 -0400238 .. method:: cursor([cursorClass])
Georg Brandl116aa622007-08-15 14:28:22 +0000239
R David Murray6db23352012-09-30 20:44:43 -0400240 The cursor method accepts a single optional parameter *cursorClass*. If
241 supplied, this must be a custom cursor class that extends
242 :class:`sqlite3.Cursor`.
Georg Brandl116aa622007-08-15 14:28:22 +0000243
R David Murray6db23352012-09-30 20:44:43 -0400244 .. method:: commit()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000245
R David Murray6db23352012-09-30 20:44:43 -0400246 This method commits the current transaction. If you don't call this method,
247 anything you did since the last call to ``commit()`` is not visible from
248 other database connections. If you wonder why you don't see the data you've
249 written to the database, please check you didn't forget to call this method.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000250
R David Murray6db23352012-09-30 20:44:43 -0400251 .. method:: rollback()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000252
R David Murray6db23352012-09-30 20:44:43 -0400253 This method rolls back any changes to the database since the last call to
254 :meth:`commit`.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000255
R David Murray6db23352012-09-30 20:44:43 -0400256 .. method:: close()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000257
R David Murray6db23352012-09-30 20:44:43 -0400258 This closes the database connection. Note that this does not automatically
259 call :meth:`commit`. If you just close your database connection without
260 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000261
R David Murray6db23352012-09-30 20:44:43 -0400262 .. method:: execute(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000263
R David Murray6db23352012-09-30 20:44:43 -0400264 This is a nonstandard shortcut that creates an intermediate cursor object by
265 calling the cursor method, then calls the cursor's :meth:`execute
266 <Cursor.execute>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268
R David Murray6db23352012-09-30 20:44:43 -0400269 .. method:: executemany(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000270
R David Murray6db23352012-09-30 20:44:43 -0400271 This is a nonstandard shortcut that creates an intermediate cursor object by
272 calling the cursor method, then calls the cursor's :meth:`executemany
273 <Cursor.executemany>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
R David Murray6db23352012-09-30 20:44:43 -0400275 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000276
R David Murray6db23352012-09-30 20:44:43 -0400277 This is a nonstandard shortcut that creates an intermediate cursor object by
278 calling the cursor method, then calls the cursor's :meth:`executescript
279 <Cursor.executescript>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281
R David Murray6db23352012-09-30 20:44:43 -0400282 .. method:: create_function(name, num_params, func)
Georg Brandl116aa622007-08-15 14:28:22 +0000283
R David Murray6db23352012-09-30 20:44:43 -0400284 Creates a user-defined function that you can later use from within SQL
285 statements under the function name *name*. *num_params* is the number of
286 parameters the function accepts, and *func* is a Python callable that is called
287 as the SQL function.
Georg Brandl116aa622007-08-15 14:28:22 +0000288
R David Murray6db23352012-09-30 20:44:43 -0400289 The function can return any of the types supported by SQLite: bytes, str, int,
290 float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000291
R David Murray6db23352012-09-30 20:44:43 -0400292 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000293
R David Murray6db23352012-09-30 20:44:43 -0400294 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296
R David Murray6db23352012-09-30 20:44:43 -0400297 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl116aa622007-08-15 14:28:22 +0000298
R David Murray6db23352012-09-30 20:44:43 -0400299 Creates a user-defined aggregate function.
Georg Brandl116aa622007-08-15 14:28:22 +0000300
R David Murray6db23352012-09-30 20:44:43 -0400301 The aggregate class must implement a ``step`` method, which accepts the number
302 of parameters *num_params*, and a ``finalize`` method which will return the
303 final result of the aggregate.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
R David Murray6db23352012-09-30 20:44:43 -0400305 The ``finalize`` method can return any of the types supported by SQLite:
306 bytes, str, int, float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000307
R David Murray6db23352012-09-30 20:44:43 -0400308 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000309
R David Murray6db23352012-09-30 20:44:43 -0400310 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312
R David Murray6db23352012-09-30 20:44:43 -0400313 .. method:: create_collation(name, callable)
Georg Brandl116aa622007-08-15 14:28:22 +0000314
R David Murray6db23352012-09-30 20:44:43 -0400315 Creates a collation with the specified *name* and *callable*. The callable will
316 be passed two string arguments. It should return -1 if the first is ordered
317 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
318 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
319 your comparisons don't affect other SQL operations.
Georg Brandl116aa622007-08-15 14:28:22 +0000320
R David Murray6db23352012-09-30 20:44:43 -0400321 Note that the callable will get its parameters as Python bytestrings, which will
322 normally be encoded in UTF-8.
Georg Brandl116aa622007-08-15 14:28:22 +0000323
R David Murray6db23352012-09-30 20:44:43 -0400324 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl116aa622007-08-15 14:28:22 +0000325
R David Murray6db23352012-09-30 20:44:43 -0400326 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl116aa622007-08-15 14:28:22 +0000327
R David Murray6db23352012-09-30 20:44:43 -0400328 To remove a collation, call ``create_collation`` with None as callable::
Georg Brandl116aa622007-08-15 14:28:22 +0000329
R David Murray6db23352012-09-30 20:44:43 -0400330 con.create_collation("reverse", None)
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332
R David Murray6db23352012-09-30 20:44:43 -0400333 .. method:: interrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000334
R David Murray6db23352012-09-30 20:44:43 -0400335 You can call this method from a different thread to abort any queries that might
336 be executing on the connection. The query will then abort and the caller will
337 get an exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339
R David Murray6db23352012-09-30 20:44:43 -0400340 .. method:: set_authorizer(authorizer_callback)
Georg Brandl116aa622007-08-15 14:28:22 +0000341
R David Murray6db23352012-09-30 20:44:43 -0400342 This routine registers a callback. The callback is invoked for each attempt to
343 access a column of a table in the database. The callback should return
344 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
345 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
346 column should be treated as a NULL value. These constants are available in the
347 :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000348
R David Murray6db23352012-09-30 20:44:43 -0400349 The first argument to the callback signifies what kind of operation is to be
350 authorized. The second and third argument will be arguments or :const:`None`
351 depending on the first argument. The 4th argument is the name of the database
352 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
353 inner-most trigger or view that is responsible for the access attempt or
354 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl116aa622007-08-15 14:28:22 +0000355
R David Murray6db23352012-09-30 20:44:43 -0400356 Please consult the SQLite documentation about the possible values for the first
357 argument and the meaning of the second and third argument depending on the first
358 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Georg Brandl116aa622007-08-15 14:28:22 +0000360
R David Murray6db23352012-09-30 20:44:43 -0400361 .. method:: set_progress_handler(handler, n)
Georg Brandl116aa622007-08-15 14:28:22 +0000362
R David Murray6db23352012-09-30 20:44:43 -0400363 This routine registers a callback. The callback is invoked for every *n*
364 instructions of the SQLite virtual machine. This is useful if you want to
365 get called from SQLite during long-running operations, for example to update
366 a GUI.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000367
R David Murray6db23352012-09-30 20:44:43 -0400368 If you want to clear any previously installed progress handler, call the
369 method with :const:`None` for *handler*.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000370
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000371
R David Murray842ca5f2012-09-30 20:49:19 -0400372 .. method:: set_trace_callback(trace_callback)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000373
R David Murray842ca5f2012-09-30 20:49:19 -0400374 Registers *trace_callback* to be called for each SQL statement that is
375 actually executed by the SQLite backend.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200376
R David Murray842ca5f2012-09-30 20:49:19 -0400377 The only argument passed to the callback is the statement (as string) that
378 is being executed. The return value of the callback is ignored. Note that
379 the backend does not only run statements passed to the :meth:`Cursor.execute`
380 methods. Other sources include the transaction management of the Python
381 module and the execution of triggers defined in the current database.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200382
R David Murray842ca5f2012-09-30 20:49:19 -0400383 Passing :const:`None` as *trace_callback* will disable the trace callback.
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200384
R David Murray842ca5f2012-09-30 20:49:19 -0400385 .. versionadded:: 3.3
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200386
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200387
R David Murray6db23352012-09-30 20:44:43 -0400388 .. method:: enable_load_extension(enabled)
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200389
R David Murray6db23352012-09-30 20:44:43 -0400390 This routine allows/disallows the SQLite engine to load SQLite extensions
391 from shared libraries. SQLite extensions can define new functions,
392 aggregates or whole new virtual table implementations. One well-known
393 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000394
R David Murray6db23352012-09-30 20:44:43 -0400395 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000396
R David Murray6db23352012-09-30 20:44:43 -0400397 .. versionadded:: 3.2
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200398
R David Murray6db23352012-09-30 20:44:43 -0400399 .. literalinclude:: ../includes/sqlite3/load_extension.py
Georg Brandl67b21b72010-08-17 15:07:14 +0000400
R David Murray6db23352012-09-30 20:44:43 -0400401 .. method:: load_extension(path)
Gerhard Häringf9cee222010-03-05 15:20:03 +0000402
R David Murray6db23352012-09-30 20:44:43 -0400403 This routine loads a SQLite extension from a shared library. You have to
404 enable extension loading with :meth:`enable_load_extension` before you can
405 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000406
R David Murray6db23352012-09-30 20:44:43 -0400407 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000408
R David Murray6db23352012-09-30 20:44:43 -0400409 .. versionadded:: 3.2
Gerhard Häringe0941c52010-10-03 21:47:06 +0000410
R David Murray6db23352012-09-30 20:44:43 -0400411 .. attribute:: row_factory
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200412
R David Murray6db23352012-09-30 20:44:43 -0400413 You can change this attribute to a callable that accepts the cursor and the
414 original row as a tuple and will return the real result row. This way, you can
415 implement more advanced ways of returning results, such as returning an object
416 that can also access columns by name.
Georg Brandl116aa622007-08-15 14:28:22 +0000417
R David Murray6db23352012-09-30 20:44:43 -0400418 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000419
R David Murray6db23352012-09-30 20:44:43 -0400420 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000421
R David Murray6db23352012-09-30 20:44:43 -0400422 If returning a tuple doesn't suffice and you want name-based access to
423 columns, you should consider setting :attr:`row_factory` to the
424 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
425 index-based and case-insensitive name-based access to columns with almost no
426 memory overhead. It will probably be better than your own custom
427 dictionary-based approach or even a db_row based solution.
Georg Brandl116aa622007-08-15 14:28:22 +0000428
R David Murray6db23352012-09-30 20:44:43 -0400429 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Georg Brandl116aa622007-08-15 14:28:22 +0000431
R David Murray6db23352012-09-30 20:44:43 -0400432 .. attribute:: text_factory
Georg Brandl116aa622007-08-15 14:28:22 +0000433
R David Murray6db23352012-09-30 20:44:43 -0400434 Using this attribute you can control what objects are returned for the ``TEXT``
435 data type. By default, this attribute is set to :class:`str` and the
436 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
437 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000438
R David Murray6db23352012-09-30 20:44:43 -0400439 For efficiency reasons, there's also a way to return :class:`str` objects
440 only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
441 this attribute to :const:`sqlite3.OptimizedUnicode`.
Georg Brandl116aa622007-08-15 14:28:22 +0000442
R David Murray6db23352012-09-30 20:44:43 -0400443 You can also set it to any other callable that accepts a single bytestring
444 parameter and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000445
R David Murray6db23352012-09-30 20:44:43 -0400446 See the following example code for illustration:
Georg Brandl116aa622007-08-15 14:28:22 +0000447
R David Murray6db23352012-09-30 20:44:43 -0400448 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450
R David Murray6db23352012-09-30 20:44:43 -0400451 .. attribute:: total_changes
Georg Brandl116aa622007-08-15 14:28:22 +0000452
R David Murray6db23352012-09-30 20:44:43 -0400453 Returns the total number of database rows that have been modified, inserted, or
454 deleted since the database connection was opened.
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456
R David Murray6db23352012-09-30 20:44:43 -0400457 .. attribute:: iterdump
Christian Heimesbbe741d2008-03-28 10:53:29 +0000458
R David Murray6db23352012-09-30 20:44:43 -0400459 Returns an iterator to dump the database in an SQL text format. Useful when
460 saving an in-memory database for later restoration. This function provides
461 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
462 shell.
Christian Heimesbbe741d2008-03-28 10:53:29 +0000463
R David Murray6db23352012-09-30 20:44:43 -0400464 Example::
Christian Heimesbbe741d2008-03-28 10:53:29 +0000465
R David Murray6db23352012-09-30 20:44:43 -0400466 # Convert file existing_db.db to SQL dump file dump.sql
467 import sqlite3, os
Christian Heimesbbe741d2008-03-28 10:53:29 +0000468
R David Murray6db23352012-09-30 20:44:43 -0400469 con = sqlite3.connect('existing_db.db')
470 with open('dump.sql', 'w') as f:
471 for line in con.iterdump():
472 f.write('%s\n' % line)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000473
474
Georg Brandl116aa622007-08-15 14:28:22 +0000475.. _sqlite3-cursor-objects:
476
477Cursor Objects
478--------------
479
Georg Brandl96115fb22010-10-17 09:33:24 +0000480.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000481
Georg Brandl96115fb22010-10-17 09:33:24 +0000482 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000483
R David Murray6db23352012-09-30 20:44:43 -0400484 .. method:: execute(sql, [parameters])
Georg Brandl116aa622007-08-15 14:28:22 +0000485
R David Murray6db23352012-09-30 20:44:43 -0400486 Executes an SQL statement. The SQL statement may be parametrized (i. e.
487 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
488 kinds of placeholders: question marks (qmark style) and named placeholders
489 (named style).
Georg Brandl116aa622007-08-15 14:28:22 +0000490
R David Murray6db23352012-09-30 20:44:43 -0400491 Here's an example of both styles:
Georg Brandl116aa622007-08-15 14:28:22 +0000492
R David Murray6db23352012-09-30 20:44:43 -0400493 .. literalinclude:: ../includes/sqlite3/execute_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000494
R David Murray6db23352012-09-30 20:44:43 -0400495 :meth:`execute` will only execute a single SQL statement. If you try to execute
496 more than one statement with it, it will raise a Warning. Use
497 :meth:`executescript` if you want to execute multiple SQL statements with one
498 call.
Georg Brandl116aa622007-08-15 14:28:22 +0000499
500
R David Murray6db23352012-09-30 20:44:43 -0400501 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl116aa622007-08-15 14:28:22 +0000502
R David Murray6db23352012-09-30 20:44:43 -0400503 Executes an SQL command against all parameter sequences or mappings found in
504 the sequence *sql*. The :mod:`sqlite3` module also allows using an
505 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000506
R David Murray6db23352012-09-30 20:44:43 -0400507 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl116aa622007-08-15 14:28:22 +0000508
R David Murray6db23352012-09-30 20:44:43 -0400509 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000510
R David Murray6db23352012-09-30 20:44:43 -0400511 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513
R David Murray6db23352012-09-30 20:44:43 -0400514 .. method:: executescript(sql_script)
Georg Brandl116aa622007-08-15 14:28:22 +0000515
R David Murray6db23352012-09-30 20:44:43 -0400516 This is a nonstandard convenience method for executing multiple SQL statements
517 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
518 gets as a parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000519
R David Murray6db23352012-09-30 20:44:43 -0400520 *sql_script* can be an instance of :class:`str` or :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000521
R David Murray6db23352012-09-30 20:44:43 -0400522 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000523
R David Murray6db23352012-09-30 20:44:43 -0400524 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526
R David Murray6db23352012-09-30 20:44:43 -0400527 .. method:: fetchone()
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000528
R David Murray6db23352012-09-30 20:44:43 -0400529 Fetches the next row of a query result set, returning a single sequence,
530 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000531
532
R David Murray6db23352012-09-30 20:44:43 -0400533 .. method:: fetchmany(size=cursor.arraysize)
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000534
R David Murray6db23352012-09-30 20:44:43 -0400535 Fetches the next set of rows of a query result, returning a list. An empty
536 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000537
R David Murray6db23352012-09-30 20:44:43 -0400538 The number of rows to fetch per call is specified by the *size* parameter.
539 If it is not given, the cursor's arraysize determines the number of rows
540 to be fetched. The method should try to fetch as many rows as indicated by
541 the size parameter. If this is not possible due to the specified number of
542 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000543
R David Murray6db23352012-09-30 20:44:43 -0400544 Note there are performance considerations involved with the *size* parameter.
545 For optimal performance, it is usually best to use the arraysize attribute.
546 If the *size* parameter is used, then it is best for it to retain the same
547 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000548
R David Murray6db23352012-09-30 20:44:43 -0400549 .. method:: fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000550
R David Murray6db23352012-09-30 20:44:43 -0400551 Fetches all (remaining) rows of a query result, returning a list. Note that
552 the cursor's arraysize attribute can affect the performance of this operation.
553 An empty list is returned when no rows are available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000554
555
R David Murray6db23352012-09-30 20:44:43 -0400556 .. attribute:: rowcount
Georg Brandl116aa622007-08-15 14:28:22 +0000557
R David Murray6db23352012-09-30 20:44:43 -0400558 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
559 attribute, the database engine's own support for the determination of "rows
560 affected"/"rows selected" is quirky.
Georg Brandl116aa622007-08-15 14:28:22 +0000561
R David Murray6db23352012-09-30 20:44:43 -0400562 For :meth:`executemany` statements, the number of modifications are summed up
563 into :attr:`rowcount`.
Georg Brandl116aa622007-08-15 14:28:22 +0000564
R David Murray6db23352012-09-30 20:44:43 -0400565 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
566 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
567 last operation is not determinable by the interface". This includes ``SELECT``
568 statements because we cannot determine the number of rows a query produced
569 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000570
R David Murray6db23352012-09-30 20:44:43 -0400571 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
572 you make a ``DELETE FROM table`` without any condition.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000573
R David Murray6db23352012-09-30 20:44:43 -0400574 .. attribute:: lastrowid
Gerhard Häringd3372792008-03-29 19:13:55 +0000575
R David Murray6db23352012-09-30 20:44:43 -0400576 This read-only attribute provides the rowid of the last modified row. It is
577 only set if you issued a ``INSERT`` statement using the :meth:`execute`
578 method. For operations other than ``INSERT`` or when :meth:`executemany` is
579 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl116aa622007-08-15 14:28:22 +0000580
R David Murray6db23352012-09-30 20:44:43 -0400581 .. attribute:: description
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000582
R David Murray6db23352012-09-30 20:44:43 -0400583 This read-only attribute provides the column names of the last query. To
584 remain compatible with the Python DB API, it returns a 7-tuple for each
585 column where the last six items of each tuple are :const:`None`.
Georg Brandl48310cd2009-01-03 21:18:54 +0000586
R David Murray6db23352012-09-30 20:44:43 -0400587 It is set for ``SELECT`` statements without any matching rows as well.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000588
589.. _sqlite3-row-objects:
590
591Row Objects
592-----------
593
594.. class:: Row
595
596 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000597 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000598 It tries to mimic a tuple in most of its features.
599
600 It supports mapping access by column name and index, iteration,
601 representation, equality testing and :func:`len`.
602
603 If two :class:`Row` objects have exactly the same columns and their
604 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000605
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000606 .. method:: keys
607
608 This method returns a tuple of column names. Immediately after a query,
609 it is the first member of each tuple in :attr:`Cursor.description`.
610
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000611Let's assume we initialize a table as in the example given above::
612
Senthil Kumaran946eb862011-07-03 10:17:22 -0700613 conn = sqlite3.connect(":memory:")
614 c = conn.cursor()
615 c.execute('''create table stocks
616 (date text, trans text, symbol text,
617 qty real, price real)''')
618 c.execute("""insert into stocks
619 values ('2006-01-05','BUY','RHAT',100,35.14)""")
620 conn.commit()
621 c.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000622
623Now we plug :class:`Row` in::
624
Senthil Kumaran946eb862011-07-03 10:17:22 -0700625 >>> conn.row_factory = sqlite3.Row
626 >>> c = conn.cursor()
627 >>> c.execute('select * from stocks')
628 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
629 >>> r = c.fetchone()
630 >>> type(r)
631 <class 'sqlite3.Row'>
632 >>> tuple(r)
633 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
634 >>> len(r)
635 5
636 >>> r[2]
637 'RHAT'
638 >>> r.keys()
639 ['date', 'trans', 'symbol', 'qty', 'price']
640 >>> r['qty']
641 100.0
642 >>> for member in r:
643 ... print(member)
644 ...
645 2006-01-05
646 BUY
647 RHAT
648 100.0
649 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000650
651
Georg Brandl116aa622007-08-15 14:28:22 +0000652.. _sqlite3-types:
653
654SQLite and Python types
655-----------------------
656
657
658Introduction
659^^^^^^^^^^^^
660
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000661SQLite natively supports the following types: ``NULL``, ``INTEGER``,
662``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000663
664The following Python types can thus be sent to SQLite without any problem:
665
Georg Brandlf6945182008-02-01 11:56:49 +0000666+-------------------------------+-------------+
667| Python type | SQLite type |
668+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000669| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000670+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000671| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000672+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000673| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000674+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000675| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000676+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000677| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000678+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000679
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000680
Georg Brandl116aa622007-08-15 14:28:22 +0000681This is how SQLite types are converted to Python types by default:
682
683+-------------+---------------------------------------------+
684| SQLite type | Python type |
685+=============+=============================================+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000686| ``NULL`` | :const:`None` |
Georg Brandl116aa622007-08-15 14:28:22 +0000687+-------------+---------------------------------------------+
Ezio Melottib5845052009-09-13 05:49:25 +0000688| ``INTEGER`` | :class:`int` |
Georg Brandl116aa622007-08-15 14:28:22 +0000689+-------------+---------------------------------------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000690| ``REAL`` | :class:`float` |
Georg Brandl116aa622007-08-15 14:28:22 +0000691+-------------+---------------------------------------------+
Georg Brandlf6945182008-02-01 11:56:49 +0000692| ``TEXT`` | depends on text_factory, str by default |
Georg Brandl116aa622007-08-15 14:28:22 +0000693+-------------+---------------------------------------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000694| ``BLOB`` | :class:`bytes` |
Georg Brandl116aa622007-08-15 14:28:22 +0000695+-------------+---------------------------------------------+
696
697The type system of the :mod:`sqlite3` module is extensible in two ways: you can
698store additional Python types in a SQLite database via object adaptation, and
699you can let the :mod:`sqlite3` module convert SQLite types to different Python
700types via converters.
701
702
703Using adapters to store additional Python types in SQLite databases
704^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
705
706As described before, SQLite supports only a limited set of types natively. To
707use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000708sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000709str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711The :mod:`sqlite3` module uses Python object adaptation, as described in
712:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
713
714There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
715type to one of the supported ones.
716
717
718Letting your object adapt itself
719""""""""""""""""""""""""""""""""
720
721This is a good approach if you write the class yourself. Let's suppose you have
722a class like this::
723
Éric Araujo28053fb2010-11-22 03:09:19 +0000724 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000725 def __init__(self, x, y):
726 self.x, self.y = x, y
727
728Now you want to store the point in a single SQLite column. First you'll have to
729choose one of the supported types first to be used for representing the point.
730Let's just use str and separate the coordinates using a semicolon. Then you need
731to give your class a method ``__conform__(self, protocol)`` which must return
732the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
733
734.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
735
736
737Registering an adapter callable
738"""""""""""""""""""""""""""""""
739
740The other possibility is to create a function that converts the type to the
741string representation and register the function with :meth:`register_adapter`.
742
Georg Brandl116aa622007-08-15 14:28:22 +0000743.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
744
745The :mod:`sqlite3` module has two default adapters for Python's built-in
746:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
747we want to store :class:`datetime.datetime` objects not in ISO representation,
748but as a Unix timestamp.
749
750.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
751
752
753Converting SQLite values to custom Python types
754^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
755
756Writing an adapter lets you send custom Python types to SQLite. But to make it
757really useful we need to make the Python to SQLite to Python roundtrip work.
758
759Enter converters.
760
761Let's go back to the :class:`Point` class. We stored the x and y coordinates
762separated via semicolons as strings in SQLite.
763
764First, we'll define a converter function that accepts the string as a parameter
765and constructs a :class:`Point` object from it.
766
767.. note::
768
769 Converter functions **always** get called with a string, no matter under which
770 data type you sent the value to SQLite.
771
Georg Brandl116aa622007-08-15 14:28:22 +0000772::
773
774 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200775 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +0000776 return Point(x, y)
777
778Now you need to make the :mod:`sqlite3` module know that what you select from
779the database is actually a point. There are two ways of doing this:
780
781* Implicitly via the declared type
782
783* Explicitly via the column name
784
785Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
786for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
787
788The following example illustrates both approaches.
789
790.. literalinclude:: ../includes/sqlite3/converter_point.py
791
792
793Default adapters and converters
794^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
795
796There are default adapters for the date and datetime types in the datetime
797module. They will be sent as ISO dates/ISO timestamps to SQLite.
798
799The default converters are registered under the name "date" for
800:class:`datetime.date` and under the name "timestamp" for
801:class:`datetime.datetime`.
802
803This way, you can use date/timestamps from Python without any additional
804fiddling in most cases. The format of the adapters is also compatible with the
805experimental SQLite date/time functions.
806
807The following example demonstrates this.
808
809.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
810
811
812.. _sqlite3-controlling-transactions:
813
814Controlling Transactions
815------------------------
816
817By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandl48310cd2009-01-03 21:18:54 +0000818Data Modification Language (DML) statement (i.e.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000819``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
820implicitly before a non-DML, non-query statement (i. e.
821anything other than ``SELECT`` or the aforementioned).
Georg Brandl116aa622007-08-15 14:28:22 +0000822
823So if you are within a transaction and issue a command like ``CREATE TABLE
824...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
825before executing that command. There are two reasons for doing that. The first
826is that some of these commands don't work within transactions. The other reason
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000827is that sqlite3 needs to keep track of the transaction state (if a transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000828is active or not). The current transaction state is exposed through the
829:attr:`Connection.in_transaction` attribute of the connection object.
Georg Brandl116aa622007-08-15 14:28:22 +0000830
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000831You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl116aa622007-08-15 14:28:22 +0000832(or none at all) via the *isolation_level* parameter to the :func:`connect`
833call, or via the :attr:`isolation_level` property of connections.
834
835If you want **autocommit mode**, then set :attr:`isolation_level` to None.
836
837Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandla971c652008-11-07 09:39:56 +0000838statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
839"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl116aa622007-08-15 14:28:22 +0000840
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000843Using :mod:`sqlite3` efficiently
844--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000845
846
847Using shortcut methods
848^^^^^^^^^^^^^^^^^^^^^^
849
850Using the nonstandard :meth:`execute`, :meth:`executemany` and
851:meth:`executescript` methods of the :class:`Connection` object, your code can
852be written more concisely because you don't have to create the (often
853superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
854objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000855objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +0000856directly using only a single call on the :class:`Connection` object.
857
858.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
859
860
861Accessing columns by name instead of by index
862^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
863
Georg Brandl22b34312009-07-26 14:54:51 +0000864One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000865:class:`sqlite3.Row` class designed to be used as a row factory.
866
867Rows wrapped with this class can be accessed both by index (like tuples) and
868case-insensitively by name:
869
870.. literalinclude:: ../includes/sqlite3/rowclass.py
871
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000872
873Using the connection as a context manager
874^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
875
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000876Connection objects can be used as context managers
877that automatically commit or rollback transactions. In the event of an
878exception, the transaction is rolled back; otherwise, the transaction is
879committed:
880
881.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +0000882
883
884Common issues
885-------------
886
887Multithreading
888^^^^^^^^^^^^^^
889
890Older SQLite versions had issues with sharing connections between threads.
891That's why the Python module disallows sharing connections and cursors between
892threads. If you still try to do so, you will get an exception at runtime.
893
894The only exception is calling the :meth:`~Connection.interrupt` method, which
895only makes sense to call from a different thread.
896
Gerhard Häringe0941c52010-10-03 21:47:06 +0000897.. rubric:: Footnotes
898
899.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumaran946eb862011-07-03 10:17:22 -0700900 default, because some platforms (notably Mac OS X) have SQLite
901 libraries which are compiled without this feature. To get loadable
902 extension support, you must pass --enable-loadable-sqlite-extensions to
903 configure.