blob: c32bb907114ae92ecdad37127bcbf41fac445207 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Lehtinena15a8d22012-03-01 21:28:00 +02006.. sectionauthor:: Gerhard Häring <gh@ghaering.de>
Georg Brandl8ec7f652007-08-15 14:28:01 +00007
8
9.. versionadded:: 2.5
10
11SQLite is a C library that provides a lightweight disk-based database that
12doesn't require a separate server process and allows accessing the database
13using a nonstandard variant of the SQL query language. Some applications can use
14SQLite for internal data storage. It's also possible to prototype an
15application using SQLite and then port the code to a larger database such as
16PostgreSQL or Oracle.
17
Raymond Hettinger094c33f2012-04-18 00:25:32 -040018The sqlite3 module was written by Gerhard Häring. It provides a SQL interface
19compliant with the DB-API 2.0 specification described by :pep:`249`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000020
21To use the module, you must first create a :class:`Connection` object that
22represents the database. Here the data will be stored in the
Raymond Hettinger094c33f2012-04-18 00:25:32 -040023:file:`example.db` file::
Georg Brandl8ec7f652007-08-15 14:28:01 +000024
Raymond Hettinger81a55c02012-02-01 13:32:45 -080025 import sqlite3
Raymond Hettinger33c66302012-04-17 22:48:06 -040026 conn = sqlite3.connect('example.db')
Georg Brandl8ec7f652007-08-15 14:28:01 +000027
28You can also supply the special name ``:memory:`` to create a database in RAM.
29
30Once you have a :class:`Connection`, you can create a :class:`Cursor` object
Georg Brandl26497d92008-10-08 17:20:20 +000031and call its :meth:`~Cursor.execute` method to perform SQL commands::
Georg Brandl8ec7f652007-08-15 14:28:01 +000032
33 c = conn.cursor()
34
35 # Create table
Raymond Hettinger33c66302012-04-17 22:48:06 -040036 c.execute('''CREATE TABLE stocks
37 (date text, trans text, symbol text, qty real, price real)''')
Georg Brandl8ec7f652007-08-15 14:28:01 +000038
39 # Insert a row of data
Raymond Hettinger33c66302012-04-17 22:48:06 -040040 c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
Georg Brandl8ec7f652007-08-15 14:28:01 +000041
42 # Save (commit) the changes
43 conn.commit()
44
Raymond Hettinger1b432742012-09-25 19:57:50 -040045 # We can also close the connection if we are done with it.
46 # Just be sure any changes have been committed or they will be lost.
47 conn.close()
Georg Brandl8ec7f652007-08-15 14:28:01 +000048
Raymond Hettinger0e15a6e2012-04-17 15:03:20 -040049The data you've saved is persistent and is available in subsequent sessions::
50
51 import sqlite3
Raymond Hettinger33c66302012-04-17 22:48:06 -040052 conn = sqlite3.connect('example.db')
Raymond Hettinger0e15a6e2012-04-17 15:03:20 -040053 c = conn.cursor()
54
Raymond Hettinger33c66302012-04-17 22:48:06 -040055Usually your SQL operations will need to use values from Python variables. You
56shouldn't assemble your query using Python's string operations because doing so
57is insecure; it makes your program vulnerable to an SQL injection attack
58(see http://xkcd.com/327/ for humorous example of what can go wrong).
59
Georg Brandl8ec7f652007-08-15 14:28:01 +000060Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
61wherever you want to use a value, and then provide a tuple of values as the
Georg Brandl498a9b32009-05-20 18:31:14 +000062second argument to the cursor's :meth:`~Cursor.execute` method. (Other database
63modules may use a different placeholder, such as ``%s`` or ``:1``.) For
64example::
Georg Brandl8ec7f652007-08-15 14:28:01 +000065
66 # Never do this -- insecure!
Raymond Hettinger33c66302012-04-17 22:48:06 -040067 symbol = 'RHAT'
68 c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
Georg Brandl8ec7f652007-08-15 14:28:01 +000069
70 # Do this instead
R David Murray07f6ea52012-08-20 14:17:22 -040071 t = ('RHAT',)
Raymond Hettinger33c66302012-04-17 22:48:06 -040072 c.execute('SELECT * FROM stocks WHERE symbol=?', t)
73 print c.fetchone()
Georg Brandl8ec7f652007-08-15 14:28:01 +000074
Raymond Hettinger33c66302012-04-17 22:48:06 -040075 # Larger example that inserts many records at a time
76 purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
77 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
78 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
79 ]
80 c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
Georg Brandl8ec7f652007-08-15 14:28:01 +000081
Georg Brandle7a09902007-10-21 12:10:28 +000082To retrieve data after executing a SELECT statement, you can either treat the
Georg Brandl26497d92008-10-08 17:20:20 +000083cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
84retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandle7a09902007-10-21 12:10:28 +000085matching rows.
Georg Brandl8ec7f652007-08-15 14:28:01 +000086
87This example uses the iterator form::
88
Raymond Hettinger33c66302012-04-17 22:48:06 -040089 >>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
90 print row
91
Mark Dickinson6b87f112009-11-24 14:27:02 +000092 (u'2006-01-05', u'BUY', u'RHAT', 100, 35.14)
Georg Brandl8ec7f652007-08-15 14:28:01 +000093 (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
94 (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
Raymond Hettingera0ff91c2012-01-10 09:51:51 +000095 (u'2006-04-05', u'BUY', u'MSFT', 1000, 72.0)
Georg Brandl8ec7f652007-08-15 14:28:01 +000096
97
98.. seealso::
99
Michael Foordabe63312010-03-02 14:22:15 +0000100 http://code.google.com/p/pysqlite/
Georg Brandl498a9b32009-05-20 18:31:14 +0000101 The pysqlite web page -- sqlite3 is developed externally under the name
102 "pysqlite".
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103
104 http://www.sqlite.org
Georg Brandl498a9b32009-05-20 18:31:14 +0000105 The SQLite web page; the documentation describes the syntax and the
106 available data types for the supported SQL dialect.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000107
Raymond Hettinger33c66302012-04-17 22:48:06 -0400108 http://www.w3schools.com/sql/
109 Tutorial, reference and examples for learning SQL syntax.
110
Georg Brandl8ec7f652007-08-15 14:28:01 +0000111 :pep:`249` - Database API Specification 2.0
112 PEP written by Marc-André Lemburg.
113
114
115.. _sqlite3-module-contents:
116
117Module functions and constants
118------------------------------
119
120
R David Murraybcd99712013-01-10 20:22:57 -0500121.. data:: version
122
123 The version number of this module, as a string. This is not the version of
124 the SQLite library.
125
126.. data:: version_info
127
128 The version number of this module, as a tuple of integers. This is not the
129 version of the SQLite library.
130
131.. data:: sqlite_version
132
133 The version number of the run-time SQLite library, as a string.
134
135.. data:: sqlite_version_info
136
137 The version number of the run-time SQLite library, as a tuple of integers.
138
Georg Brandl8ec7f652007-08-15 14:28:01 +0000139.. data:: PARSE_DECLTYPES
140
141 This constant is meant to be used with the *detect_types* parameter of the
142 :func:`connect` function.
143
144 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Gerhard Häringe11c9b32008-05-04 13:42:44 +0000145 column it returns. It will parse out the first word of the declared type,
146 i. e. for "integer primary key", it will parse out "integer", or for
147 "number(10)" it will parse out "number". Then for that column, it will look
148 into the converters dictionary and use the converter function registered for
149 that type there.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
151
152.. data:: PARSE_COLNAMES
153
154 This constant is meant to be used with the *detect_types* parameter of the
155 :func:`connect` function.
156
157 Setting this makes the SQLite interface parse the column name for each column it
158 returns. It will look for a string formed [mytype] in there, and then decide
159 that 'mytype' is the type of the column. It will try to find an entry of
160 'mytype' in the converters dictionary and then use the converter function found
Georg Brandl26497d92008-10-08 17:20:20 +0000161 there to return the value. The column name found in :attr:`Cursor.description`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000162 is only the first word of the column name, i. e. if you use something like
163 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
164 first blank for the column name: the column name would simply be "x".
165
166
Georg Brandle85e1ae2010-10-06 09:17:24 +0000167.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000168
169 Opens a connection to the SQLite database file *database*. You can use
170 ``":memory:"`` to open a database connection to a database that resides in RAM
171 instead of on disk.
172
173 When a database is accessed by multiple connections, and one of the processes
174 modifies the database, the SQLite database is locked until that transaction is
175 committed. The *timeout* parameter specifies how long the connection should wait
176 for the lock to go away until raising an exception. The default for the timeout
177 parameter is 5.0 (five seconds).
178
179 For the *isolation_level* parameter, please see the
180 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
181
182 SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
183 you want to use other types you must add support for them yourself. The
184 *detect_types* parameter and the using custom **converters** registered with the
185 module-level :func:`register_converter` function allow you to easily do that.
186
187 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
188 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
189 type detection on.
190
191 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
192 connect call. You can, however, subclass the :class:`Connection` class and make
193 :func:`connect` use your class instead by providing your class for the *factory*
194 parameter.
195
196 Consult the section :ref:`sqlite3-types` of this manual for details.
197
198 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
199 overhead. If you want to explicitly set the number of statements that are cached
200 for the connection, you can set the *cached_statements* parameter. The currently
201 implemented default is to cache 100 statements.
202
203
204.. function:: register_converter(typename, callable)
205
206 Registers a callable to convert a bytestring from the database into a custom
207 Python type. The callable will be invoked for all database values that are of
208 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
209 function for how the type detection works. Note that the case of *typename* and
210 the name of the type in your query must match!
211
212
213.. function:: register_adapter(type, callable)
214
215 Registers a callable to convert the custom Python type *type* into one of
216 SQLite's supported types. The callable *callable* accepts as single parameter
217 the Python value, and must return a value of the following types: int, long,
218 float, str (UTF-8 encoded), unicode or buffer.
219
220
221.. function:: complete_statement(sql)
222
223 Returns :const:`True` if the string *sql* contains one or more complete SQL
224 statements terminated by semicolons. It does not verify that the SQL is
225 syntactically correct, only that there are no unclosed string literals and the
226 statement is terminated by a semicolon.
227
228 This can be used to build a shell for SQLite, as in the following example:
229
230
231 .. literalinclude:: ../includes/sqlite3/complete_statement.py
232
233
234.. function:: enable_callback_tracebacks(flag)
235
236 By default you will not get any tracebacks in user-defined functions,
237 aggregates, converters, authorizer callbacks etc. If you want to debug them, you
238 can call this function with *flag* as True. Afterwards, you will get tracebacks
239 from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
240 again.
241
242
243.. _sqlite3-connection-objects:
244
245Connection Objects
246------------------
247
Georg Brandl26497d92008-10-08 17:20:20 +0000248.. class:: Connection
249
250 A SQLite database connection has the following attributes and methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000251
R David Murray95d7cdf2012-09-30 21:04:46 -0400252 .. attribute:: isolation_level
Georg Brandl8ec7f652007-08-15 14:28:01 +0000253
R David Murray95d7cdf2012-09-30 21:04:46 -0400254 Get or set the current isolation level. :const:`None` for autocommit mode or
255 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
256 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000257
258
R David Murray95d7cdf2012-09-30 21:04:46 -0400259 .. method:: cursor([cursorClass])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000260
R David Murray95d7cdf2012-09-30 21:04:46 -0400261 The cursor method accepts a single optional parameter *cursorClass*. If
262 supplied, this must be a custom cursor class that extends
263 :class:`sqlite3.Cursor`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000264
R David Murray95d7cdf2012-09-30 21:04:46 -0400265 .. method:: commit()
Gerhard Häring41309302008-03-29 01:27:37 +0000266
R David Murray95d7cdf2012-09-30 21:04:46 -0400267 This method commits the current transaction. If you don't call this method,
268 anything you did since the last call to ``commit()`` is not visible from
269 other database connections. If you wonder why you don't see the data you've
270 written to the database, please check you didn't forget to call this method.
Gerhard Häring41309302008-03-29 01:27:37 +0000271
R David Murray95d7cdf2012-09-30 21:04:46 -0400272 .. method:: rollback()
Gerhard Häring41309302008-03-29 01:27:37 +0000273
R David Murray95d7cdf2012-09-30 21:04:46 -0400274 This method rolls back any changes to the database since the last call to
275 :meth:`commit`.
Gerhard Häring41309302008-03-29 01:27:37 +0000276
R David Murray95d7cdf2012-09-30 21:04:46 -0400277 .. method:: close()
Gerhard Häring41309302008-03-29 01:27:37 +0000278
R David Murray95d7cdf2012-09-30 21:04:46 -0400279 This closes the database connection. Note that this does not automatically
280 call :meth:`commit`. If you just close your database connection without
281 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring41309302008-03-29 01:27:37 +0000282
R David Murray95d7cdf2012-09-30 21:04:46 -0400283 .. method:: execute(sql, [parameters])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284
R David Murray95d7cdf2012-09-30 21:04:46 -0400285 This is a nonstandard shortcut that creates an intermediate cursor object by
286 calling the cursor method, then calls the cursor's :meth:`execute
287 <Cursor.execute>` method with the parameters given.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000288
289
R David Murray95d7cdf2012-09-30 21:04:46 -0400290 .. method:: executemany(sql, [parameters])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000291
R David Murray95d7cdf2012-09-30 21:04:46 -0400292 This is a nonstandard shortcut that creates an intermediate cursor object by
293 calling the cursor method, then calls the cursor's :meth:`executemany
294 <Cursor.executemany>` method with the parameters given.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000295
R David Murray95d7cdf2012-09-30 21:04:46 -0400296 .. method:: executescript(sql_script)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000297
R David Murray95d7cdf2012-09-30 21:04:46 -0400298 This is a nonstandard shortcut that creates an intermediate cursor object by
299 calling the cursor method, then calls the cursor's :meth:`executescript
300 <Cursor.executescript>` method with the parameters given.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000301
302
R David Murray95d7cdf2012-09-30 21:04:46 -0400303 .. method:: create_function(name, num_params, func)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000304
R David Murray95d7cdf2012-09-30 21:04:46 -0400305 Creates a user-defined function that you can later use from within SQL
306 statements under the function name *name*. *num_params* is the number of
307 parameters the function accepts, and *func* is a Python callable that is called
308 as the SQL function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000309
R David Murray95d7cdf2012-09-30 21:04:46 -0400310 The function can return any of the types supported by SQLite: unicode, str, int,
311 long, float, buffer and None.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000312
R David Murray95d7cdf2012-09-30 21:04:46 -0400313 Example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000314
R David Murray95d7cdf2012-09-30 21:04:46 -0400315 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316
317
R David Murray95d7cdf2012-09-30 21:04:46 -0400318 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000319
R David Murray95d7cdf2012-09-30 21:04:46 -0400320 Creates a user-defined aggregate function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000321
R David Murray95d7cdf2012-09-30 21:04:46 -0400322 The aggregate class must implement a ``step`` method, which accepts the number
323 of parameters *num_params*, and a ``finalize`` method which will return the
324 final result of the aggregate.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000325
R David Murray95d7cdf2012-09-30 21:04:46 -0400326 The ``finalize`` method can return any of the types supported by SQLite:
327 unicode, str, int, long, float, buffer and None.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000328
R David Murray95d7cdf2012-09-30 21:04:46 -0400329 Example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000330
R David Murray95d7cdf2012-09-30 21:04:46 -0400331 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000332
333
R David Murray95d7cdf2012-09-30 21:04:46 -0400334 .. method:: create_collation(name, callable)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000335
R David Murray95d7cdf2012-09-30 21:04:46 -0400336 Creates a collation with the specified *name* and *callable*. The callable will
337 be passed two string arguments. It should return -1 if the first is ordered
338 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
339 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
340 your comparisons don't affect other SQL operations.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341
R David Murray95d7cdf2012-09-30 21:04:46 -0400342 Note that the callable will get its parameters as Python bytestrings, which will
343 normally be encoded in UTF-8.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000344
R David Murray95d7cdf2012-09-30 21:04:46 -0400345 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl8ec7f652007-08-15 14:28:01 +0000346
R David Murray95d7cdf2012-09-30 21:04:46 -0400347 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000348
R David Murray95d7cdf2012-09-30 21:04:46 -0400349 To remove a collation, call ``create_collation`` with None as callable::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000350
R David Murray95d7cdf2012-09-30 21:04:46 -0400351 con.create_collation("reverse", None)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000352
353
R David Murray95d7cdf2012-09-30 21:04:46 -0400354 .. method:: interrupt()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000355
R David Murray95d7cdf2012-09-30 21:04:46 -0400356 You can call this method from a different thread to abort any queries that might
357 be executing on the connection. The query will then abort and the caller will
358 get an exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000359
360
R David Murray95d7cdf2012-09-30 21:04:46 -0400361 .. method:: set_authorizer(authorizer_callback)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000362
R David Murray95d7cdf2012-09-30 21:04:46 -0400363 This routine registers a callback. The callback is invoked for each attempt to
364 access a column of a table in the database. The callback should return
365 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
366 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
367 column should be treated as a NULL value. These constants are available in the
368 :mod:`sqlite3` module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000369
R David Murray95d7cdf2012-09-30 21:04:46 -0400370 The first argument to the callback signifies what kind of operation is to be
371 authorized. The second and third argument will be arguments or :const:`None`
372 depending on the first argument. The 4th argument is the name of the database
373 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
374 inner-most trigger or view that is responsible for the access attempt or
375 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000376
R David Murray95d7cdf2012-09-30 21:04:46 -0400377 Please consult the SQLite documentation about the possible values for the first
378 argument and the meaning of the second and third argument depending on the first
379 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
381
R David Murray95d7cdf2012-09-30 21:04:46 -0400382 .. method:: set_progress_handler(handler, n)
Gerhard Häring41309302008-03-29 01:27:37 +0000383
R David Murray95d7cdf2012-09-30 21:04:46 -0400384 This routine registers a callback. The callback is invoked for every *n*
385 instructions of the SQLite virtual machine. This is useful if you want to
386 get called from SQLite during long-running operations, for example to update
387 a GUI.
Gerhard Häring41309302008-03-29 01:27:37 +0000388
R David Murray95d7cdf2012-09-30 21:04:46 -0400389 If you want to clear any previously installed progress handler, call the
390 method with :const:`None` for *handler*.
Gerhard Häring41309302008-03-29 01:27:37 +0000391
R David Murray95d7cdf2012-09-30 21:04:46 -0400392 .. versionadded:: 2.6
Petri Lehtinena15a8d22012-03-01 21:28:00 +0200393
Gerhard Häring41309302008-03-29 01:27:37 +0000394
R David Murray95d7cdf2012-09-30 21:04:46 -0400395 .. method:: enable_load_extension(enabled)
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000396
R David Murray95d7cdf2012-09-30 21:04:46 -0400397 This routine allows/disallows the SQLite engine to load SQLite extensions
398 from shared libraries. SQLite extensions can define new functions,
399 aggregates or whole new virtual table implementations. One well-known
400 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000401
R David Murray95d7cdf2012-09-30 21:04:46 -0400402 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000403
R David Murray95d7cdf2012-09-30 21:04:46 -0400404 .. versionadded:: 2.7
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000405
R David Murray95d7cdf2012-09-30 21:04:46 -0400406 .. literalinclude:: ../includes/sqlite3/load_extension.py
Petri Lehtinena15a8d22012-03-01 21:28:00 +0200407
R David Murray95d7cdf2012-09-30 21:04:46 -0400408 .. method:: load_extension(path)
Petri Lehtinena15a8d22012-03-01 21:28:00 +0200409
R David Murray95d7cdf2012-09-30 21:04:46 -0400410 This routine loads a SQLite extension from a shared library. You have to
411 enable extension loading with :meth:`enable_load_extension` before you can
412 use this routine.
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000413
R David Murray95d7cdf2012-09-30 21:04:46 -0400414 Loadable extensions are disabled by default. See [#f1]_.
Petri Lehtinena15a8d22012-03-01 21:28:00 +0200415
R David Murray95d7cdf2012-09-30 21:04:46 -0400416 .. versionadded:: 2.7
Senthil Kumaran7bf5ba02011-06-25 20:48:21 -0700417
R David Murray95d7cdf2012-09-30 21:04:46 -0400418 .. attribute:: row_factory
Georg Brandl8ec7f652007-08-15 14:28:01 +0000419
R David Murray95d7cdf2012-09-30 21:04:46 -0400420 You can change this attribute to a callable that accepts the cursor and the
421 original row as a tuple and will return the real result row. This way, you can
422 implement more advanced ways of returning results, such as returning an object
423 that can also access columns by name.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000424
R David Murray95d7cdf2012-09-30 21:04:46 -0400425 Example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000426
R David Murray95d7cdf2012-09-30 21:04:46 -0400427 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000428
R David Murray95d7cdf2012-09-30 21:04:46 -0400429 If returning a tuple doesn't suffice and you want name-based access to
430 columns, you should consider setting :attr:`row_factory` to the
431 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
432 index-based and case-insensitive name-based access to columns with almost no
433 memory overhead. It will probably be better than your own custom
434 dictionary-based approach or even a db_row based solution.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435
R David Murray95d7cdf2012-09-30 21:04:46 -0400436 .. XXX what's a db_row-based solution?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000437
438
R David Murray95d7cdf2012-09-30 21:04:46 -0400439 .. attribute:: text_factory
Georg Brandl8ec7f652007-08-15 14:28:01 +0000440
R David Murray95d7cdf2012-09-30 21:04:46 -0400441 Using this attribute you can control what objects are returned for the ``TEXT``
442 data type. By default, this attribute is set to :class:`unicode` and the
443 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
444 return bytestrings instead, you can set it to :class:`str`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000445
R David Murray95d7cdf2012-09-30 21:04:46 -0400446 For efficiency reasons, there's also a way to return Unicode objects only for
447 non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to
448 :const:`sqlite3.OptimizedUnicode`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000449
R David Murray95d7cdf2012-09-30 21:04:46 -0400450 You can also set it to any other callable that accepts a single bytestring
451 parameter and returns the resulting object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000452
R David Murray95d7cdf2012-09-30 21:04:46 -0400453 See the following example code for illustration:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000454
R David Murray95d7cdf2012-09-30 21:04:46 -0400455 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000456
457
R David Murray95d7cdf2012-09-30 21:04:46 -0400458 .. attribute:: total_changes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000459
R David Murray95d7cdf2012-09-30 21:04:46 -0400460 Returns the total number of database rows that have been modified, inserted, or
461 deleted since the database connection was opened.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000462
463
R David Murray95d7cdf2012-09-30 21:04:46 -0400464 .. attribute:: iterdump
Gregory P. Smithb9803422008-03-28 08:32:09 +0000465
R David Murray95d7cdf2012-09-30 21:04:46 -0400466 Returns an iterator to dump the database in an SQL text format. Useful when
467 saving an in-memory database for later restoration. This function provides
468 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
469 shell.
Gregory P. Smithb9803422008-03-28 08:32:09 +0000470
R David Murray95d7cdf2012-09-30 21:04:46 -0400471 .. versionadded:: 2.6
Gregory P. Smithb9803422008-03-28 08:32:09 +0000472
R David Murray95d7cdf2012-09-30 21:04:46 -0400473 Example::
Gregory P. Smithb9803422008-03-28 08:32:09 +0000474
R David Murray95d7cdf2012-09-30 21:04:46 -0400475 # Convert file existing_db.db to SQL dump file dump.sql
476 import sqlite3, os
Gregory P. Smithb9803422008-03-28 08:32:09 +0000477
R David Murray95d7cdf2012-09-30 21:04:46 -0400478 con = sqlite3.connect('existing_db.db')
479 with open('dump.sql', 'w') as f:
480 for line in con.iterdump():
481 f.write('%s\n' % line)
Gregory P. Smithb9803422008-03-28 08:32:09 +0000482
483
Georg Brandl8ec7f652007-08-15 14:28:01 +0000484.. _sqlite3-cursor-objects:
485
486Cursor Objects
487--------------
488
Georg Brandl26946ec2010-11-26 07:42:15 +0000489.. class:: Cursor
Georg Brandl8ec7f652007-08-15 14:28:01 +0000490
Georg Brandl26946ec2010-11-26 07:42:15 +0000491 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000492
R David Murray95d7cdf2012-09-30 21:04:46 -0400493 .. method:: execute(sql, [parameters])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000494
R David Murray95d7cdf2012-09-30 21:04:46 -0400495 Executes an SQL statement. The SQL statement may be parameterized (i. e.
496 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
497 kinds of placeholders: question marks (qmark style) and named placeholders
498 (named style).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000499
R David Murray95d7cdf2012-09-30 21:04:46 -0400500 Here's an example of both styles:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000501
R David Murray95d7cdf2012-09-30 21:04:46 -0400502 .. literalinclude:: ../includes/sqlite3/execute_1.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000503
R David Murray95d7cdf2012-09-30 21:04:46 -0400504 :meth:`execute` will only execute a single SQL statement. If you try to execute
505 more than one statement with it, it will raise a Warning. Use
506 :meth:`executescript` if you want to execute multiple SQL statements with one
507 call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000508
509
R David Murray95d7cdf2012-09-30 21:04:46 -0400510 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000511
R David Murray95d7cdf2012-09-30 21:04:46 -0400512 Executes an SQL command against all parameter sequences or mappings found in
513 the sequence *sql*. The :mod:`sqlite3` module also allows using an
514 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000515
R David Murray95d7cdf2012-09-30 21:04:46 -0400516 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000517
R David Murray95d7cdf2012-09-30 21:04:46 -0400518 Here's a shorter example using a :term:`generator`:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000519
R David Murray95d7cdf2012-09-30 21:04:46 -0400520 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000521
522
R David Murray95d7cdf2012-09-30 21:04:46 -0400523 .. method:: executescript(sql_script)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000524
R David Murray95d7cdf2012-09-30 21:04:46 -0400525 This is a nonstandard convenience method for executing multiple SQL statements
526 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
527 gets as a parameter.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000528
R David Murray95d7cdf2012-09-30 21:04:46 -0400529 *sql_script* can be a bytestring or a Unicode string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000530
R David Murray95d7cdf2012-09-30 21:04:46 -0400531 Example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000532
R David Murray95d7cdf2012-09-30 21:04:46 -0400533 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000534
535
R David Murray95d7cdf2012-09-30 21:04:46 -0400536 .. method:: fetchone()
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000537
R David Murray95d7cdf2012-09-30 21:04:46 -0400538 Fetches the next row of a query result set, returning a single sequence,
539 or :const:`None` when no more data is available.
Georg Brandlf558d2e2008-01-19 20:53:07 +0000540
541
R David Murray95d7cdf2012-09-30 21:04:46 -0400542 .. method:: fetchmany([size=cursor.arraysize])
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000543
R David Murray95d7cdf2012-09-30 21:04:46 -0400544 Fetches the next set of rows of a query result, returning a list. An empty
545 list is returned when no more rows are available.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000546
R David Murray95d7cdf2012-09-30 21:04:46 -0400547 The number of rows to fetch per call is specified by the *size* parameter.
548 If it is not given, the cursor's arraysize determines the number of rows
549 to be fetched. The method should try to fetch as many rows as indicated by
550 the size parameter. If this is not possible due to the specified number of
551 rows not being available, fewer rows may be returned.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000552
R David Murray95d7cdf2012-09-30 21:04:46 -0400553 Note there are performance considerations involved with the *size* parameter.
554 For optimal performance, it is usually best to use the arraysize attribute.
555 If the *size* parameter is used, then it is best for it to retain the same
556 value from one :meth:`fetchmany` call to the next.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000557
R David Murray95d7cdf2012-09-30 21:04:46 -0400558 .. method:: fetchall()
Georg Brandlf558d2e2008-01-19 20:53:07 +0000559
R David Murray95d7cdf2012-09-30 21:04:46 -0400560 Fetches all (remaining) rows of a query result, returning a list. Note that
561 the cursor's arraysize attribute can affect the performance of this operation.
562 An empty list is returned when no rows are available.
Georg Brandlf558d2e2008-01-19 20:53:07 +0000563
564
R David Murray95d7cdf2012-09-30 21:04:46 -0400565 .. attribute:: rowcount
Georg Brandl8ec7f652007-08-15 14:28:01 +0000566
R David Murray95d7cdf2012-09-30 21:04:46 -0400567 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
568 attribute, the database engine's own support for the determination of "rows
569 affected"/"rows selected" is quirky.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000570
R David Murray95d7cdf2012-09-30 21:04:46 -0400571 For :meth:`executemany` statements, the number of modifications are summed up
572 into :attr:`rowcount`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000573
R David Murray95d7cdf2012-09-30 21:04:46 -0400574 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
575 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
576 last operation is not determinable by the interface". This includes ``SELECT``
577 statements because we cannot determine the number of rows a query produced
578 until all rows were fetched.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000579
R David Murray95d7cdf2012-09-30 21:04:46 -0400580 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
581 you make a ``DELETE FROM table`` without any condition.
Georg Brandl891f1d32007-08-23 20:40:01 +0000582
R David Murray95d7cdf2012-09-30 21:04:46 -0400583 .. attribute:: lastrowid
Gerhard Häringc15317e2008-03-29 19:11:52 +0000584
R David Murray95d7cdf2012-09-30 21:04:46 -0400585 This read-only attribute provides the rowid of the last modified row. It is
586 only set if you issued a ``INSERT`` statement using the :meth:`execute`
587 method. For operations other than ``INSERT`` or when :meth:`executemany` is
588 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000589
R David Murray95d7cdf2012-09-30 21:04:46 -0400590 .. attribute:: description
Georg Brandl26497d92008-10-08 17:20:20 +0000591
R David Murray95d7cdf2012-09-30 21:04:46 -0400592 This read-only attribute provides the column names of the last query. To
593 remain compatible with the Python DB API, it returns a 7-tuple for each
594 column where the last six items of each tuple are :const:`None`.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000595
R David Murray95d7cdf2012-09-30 21:04:46 -0400596 It is set for ``SELECT`` statements without any matching rows as well.
Georg Brandl26497d92008-10-08 17:20:20 +0000597
598.. _sqlite3-row-objects:
599
600Row Objects
601-----------
602
603.. class:: Row
604
605 A :class:`Row` instance serves as a highly optimized
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000606 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Georg Brandl26497d92008-10-08 17:20:20 +0000607 It tries to mimic a tuple in most of its features.
608
609 It supports mapping access by column name and index, iteration,
610 representation, equality testing and :func:`len`.
611
612 If two :class:`Row` objects have exactly the same columns and their
613 members are equal, they compare equal.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000614
Georg Brandl26497d92008-10-08 17:20:20 +0000615 .. versionchanged:: 2.6
616 Added iteration and equality (hashability).
617
618 .. method:: keys
619
620 This method returns a tuple of column names. Immediately after a query,
621 it is the first member of each tuple in :attr:`Cursor.description`.
622
623 .. versionadded:: 2.6
624
625Let's assume we initialize a table as in the example given above::
626
Senthil Kumarane04d2562011-07-03 10:12:59 -0700627 conn = sqlite3.connect(":memory:")
628 c = conn.cursor()
629 c.execute('''create table stocks
630 (date text, trans text, symbol text,
631 qty real, price real)''')
632 c.execute("""insert into stocks
633 values ('2006-01-05','BUY','RHAT',100,35.14)""")
634 conn.commit()
635 c.close()
Georg Brandl26497d92008-10-08 17:20:20 +0000636
637Now we plug :class:`Row` in::
638
Senthil Kumarane04d2562011-07-03 10:12:59 -0700639 >>> conn.row_factory = sqlite3.Row
640 >>> c = conn.cursor()
641 >>> c.execute('select * from stocks')
642 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
643 >>> r = c.fetchone()
644 >>> type(r)
645 <type 'sqlite3.Row'>
646 >>> r
647 (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
648 >>> len(r)
649 5
650 >>> r[2]
651 u'RHAT'
652 >>> r.keys()
653 ['date', 'trans', 'symbol', 'qty', 'price']
654 >>> r['qty']
655 100.0
Petri Lehtinena15a8d22012-03-01 21:28:00 +0200656 >>> for member in r:
657 ... print member
Senthil Kumarane04d2562011-07-03 10:12:59 -0700658 ...
659 2006-01-05
660 BUY
661 RHAT
662 100.0
663 35.14
Georg Brandl26497d92008-10-08 17:20:20 +0000664
665
Georg Brandl8ec7f652007-08-15 14:28:01 +0000666.. _sqlite3-types:
667
668SQLite and Python types
669-----------------------
670
671
672Introduction
673^^^^^^^^^^^^
674
Georg Brandl26497d92008-10-08 17:20:20 +0000675SQLite natively supports the following types: ``NULL``, ``INTEGER``,
676``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000677
678The following Python types can thus be sent to SQLite without any problem:
679
Georg Brandl26497d92008-10-08 17:20:20 +0000680+-----------------------------+-------------+
681| Python type | SQLite type |
682+=============================+=============+
683| :const:`None` | ``NULL`` |
684+-----------------------------+-------------+
685| :class:`int` | ``INTEGER`` |
686+-----------------------------+-------------+
687| :class:`long` | ``INTEGER`` |
688+-----------------------------+-------------+
689| :class:`float` | ``REAL`` |
690+-----------------------------+-------------+
691| :class:`str` (UTF8-encoded) | ``TEXT`` |
692+-----------------------------+-------------+
693| :class:`unicode` | ``TEXT`` |
694+-----------------------------+-------------+
695| :class:`buffer` | ``BLOB`` |
696+-----------------------------+-------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000697
698This is how SQLite types are converted to Python types by default:
699
Georg Brandl26497d92008-10-08 17:20:20 +0000700+-------------+----------------------------------------------+
701| SQLite type | Python type |
702+=============+==============================================+
703| ``NULL`` | :const:`None` |
704+-------------+----------------------------------------------+
705| ``INTEGER`` | :class:`int` or :class:`long`, |
706| | depending on size |
707+-------------+----------------------------------------------+
708| ``REAL`` | :class:`float` |
709+-------------+----------------------------------------------+
710| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
711| | :class:`unicode` by default |
712+-------------+----------------------------------------------+
713| ``BLOB`` | :class:`buffer` |
714+-------------+----------------------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000715
716The type system of the :mod:`sqlite3` module is extensible in two ways: you can
717store additional Python types in a SQLite database via object adaptation, and
718you can let the :mod:`sqlite3` module convert SQLite types to different Python
719types via converters.
720
721
722Using adapters to store additional Python types in SQLite databases
723^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
724
725As described before, SQLite supports only a limited set of types natively. To
726use other Python types with SQLite, you must **adapt** them to one of the
727sqlite3 module's supported types for SQLite: one of NoneType, int, long, float,
728str, unicode, buffer.
729
730The :mod:`sqlite3` module uses Python object adaptation, as described in
731:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
732
733There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
734type to one of the supported ones.
735
736
737Letting your object adapt itself
738""""""""""""""""""""""""""""""""
739
740This is a good approach if you write the class yourself. Let's suppose you have
741a class like this::
742
743 class Point(object):
744 def __init__(self, x, y):
745 self.x, self.y = x, y
746
747Now you want to store the point in a single SQLite column. First you'll have to
748choose one of the supported types first to be used for representing the point.
749Let's just use str and separate the coordinates using a semicolon. Then you need
750to give your class a method ``__conform__(self, protocol)`` which must return
751the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
752
753.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
754
755
756Registering an adapter callable
757"""""""""""""""""""""""""""""""
758
759The other possibility is to create a function that converts the type to the
760string representation and register the function with :meth:`register_adapter`.
761
762.. note::
763
Georg Brandla7395032007-10-21 12:15:05 +0000764 The type/class to adapt must be a :term:`new-style class`, i. e. it must have
Georg Brandl8ec7f652007-08-15 14:28:01 +0000765 :class:`object` as one of its bases.
766
767.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
768
769The :mod:`sqlite3` module has two default adapters for Python's built-in
770:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
771we want to store :class:`datetime.datetime` objects not in ISO representation,
772but as a Unix timestamp.
773
774.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
775
776
777Converting SQLite values to custom Python types
778^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
779
780Writing an adapter lets you send custom Python types to SQLite. But to make it
781really useful we need to make the Python to SQLite to Python roundtrip work.
782
783Enter converters.
784
785Let's go back to the :class:`Point` class. We stored the x and y coordinates
786separated via semicolons as strings in SQLite.
787
788First, we'll define a converter function that accepts the string as a parameter
789and constructs a :class:`Point` object from it.
790
791.. note::
792
793 Converter functions **always** get called with a string, no matter under which
794 data type you sent the value to SQLite.
795
Georg Brandl8ec7f652007-08-15 14:28:01 +0000796::
797
798 def convert_point(s):
799 x, y = map(float, s.split(";"))
800 return Point(x, y)
801
802Now you need to make the :mod:`sqlite3` module know that what you select from
803the database is actually a point. There are two ways of doing this:
804
805* Implicitly via the declared type
806
807* Explicitly via the column name
808
809Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
810for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
811
812The following example illustrates both approaches.
813
814.. literalinclude:: ../includes/sqlite3/converter_point.py
815
816
817Default adapters and converters
818^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
819
820There are default adapters for the date and datetime types in the datetime
821module. They will be sent as ISO dates/ISO timestamps to SQLite.
822
823The default converters are registered under the name "date" for
824:class:`datetime.date` and under the name "timestamp" for
825:class:`datetime.datetime`.
826
827This way, you can use date/timestamps from Python without any additional
828fiddling in most cases. The format of the adapters is also compatible with the
829experimental SQLite date/time functions.
830
831The following example demonstrates this.
832
833.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
834
Petri Lehtinene41a4632013-02-26 21:32:02 +0200835If a timestamp stored in SQLite has a fractional part longer than 6
836numbers, its value will be truncated to microsecond precision by the
837timestamp converter.
838
Georg Brandl8ec7f652007-08-15 14:28:01 +0000839
840.. _sqlite3-controlling-transactions:
841
842Controlling Transactions
843------------------------
844
845By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000846Data Modification Language (DML) statement (i.e.
Georg Brandl26497d92008-10-08 17:20:20 +0000847``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
848implicitly before a non-DML, non-query statement (i. e.
849anything other than ``SELECT`` or the aforementioned).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000850
851So if you are within a transaction and issue a command like ``CREATE TABLE
852...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
853before executing that command. There are two reasons for doing that. The first
854is that some of these commands don't work within transactions. The other reason
Georg Brandl498a9b32009-05-20 18:31:14 +0000855is that sqlite3 needs to keep track of the transaction state (if a transaction
Georg Brandl8ec7f652007-08-15 14:28:01 +0000856is active or not).
857
Georg Brandl498a9b32009-05-20 18:31:14 +0000858You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000859(or none at all) via the *isolation_level* parameter to the :func:`connect`
860call, or via the :attr:`isolation_level` property of connections.
861
862If you want **autocommit mode**, then set :attr:`isolation_level` to None.
863
864Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandlb9bfea72008-11-06 10:19:11 +0000865statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
866"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl8ec7f652007-08-15 14:28:01 +0000867
Georg Brandl8ec7f652007-08-15 14:28:01 +0000868
869
Georg Brandl498a9b32009-05-20 18:31:14 +0000870Using :mod:`sqlite3` efficiently
871--------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000872
873
874Using shortcut methods
875^^^^^^^^^^^^^^^^^^^^^^
876
877Using the nonstandard :meth:`execute`, :meth:`executemany` and
878:meth:`executescript` methods of the :class:`Connection` object, your code can
879be written more concisely because you don't have to create the (often
880superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
881objects are created implicitly and these shortcut methods return the cursor
Georg Brandl26497d92008-10-08 17:20:20 +0000882objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl8ec7f652007-08-15 14:28:01 +0000883directly using only a single call on the :class:`Connection` object.
884
885.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
886
887
888Accessing columns by name instead of by index
889^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
890
Georg Brandld7d4fd72009-07-26 14:37:28 +0000891One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000892:class:`sqlite3.Row` class designed to be used as a row factory.
893
894Rows wrapped with this class can be accessed both by index (like tuples) and
895case-insensitively by name:
896
897.. literalinclude:: ../includes/sqlite3/rowclass.py
898
Gerhard Häring41309302008-03-29 01:27:37 +0000899
900Using the connection as a context manager
901^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
902
903.. versionadded:: 2.6
904
905Connection objects can be used as context managers
906that automatically commit or rollback transactions. In the event of an
907exception, the transaction is rolled back; otherwise, the transaction is
908committed:
909
910.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häring5f5c15f2010-08-06 06:14:12 +0000911
912
913Common issues
914-------------
915
916Multithreading
917^^^^^^^^^^^^^^
918
919Older SQLite versions had issues with sharing connections between threads.
920That's why the Python module disallows sharing connections and cursors between
921threads. If you still try to do so, you will get an exception at runtime.
922
923The only exception is calling the :meth:`~Connection.interrupt` method, which
924only makes sense to call from a different thread.
Senthil Kumaran7bf5ba02011-06-25 20:48:21 -0700925
926.. rubric:: Footnotes
927
928.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumarane04d2562011-07-03 10:12:59 -0700929 default, because some platforms (notably Mac OS X) have SQLite libraries
930 which are compiled without this feature. To get loadable extension support,
931 you must modify setup.py and remove the line that sets
932 SQLITE_OMIT_LOAD_EXTENSION.
Senthil Kumaran7bf5ba02011-06-25 20:48:21 -0700933