blob: ba51e48bc8dbb5d76f3458403001612917e00080 [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
121.. data:: PARSE_DECLTYPES
122
123 This constant is meant to be used with the *detect_types* parameter of the
124 :func:`connect` function.
125
126 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Gerhard Häringe11c9b32008-05-04 13:42:44 +0000127 column it returns. It will parse out the first word of the declared type,
128 i. e. for "integer primary key", it will parse out "integer", or for
129 "number(10)" it will parse out "number". Then for that column, it will look
130 into the converters dictionary and use the converter function registered for
131 that type there.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000132
133
134.. data:: PARSE_COLNAMES
135
136 This constant is meant to be used with the *detect_types* parameter of the
137 :func:`connect` function.
138
139 Setting this makes the SQLite interface parse the column name for each column it
140 returns. It will look for a string formed [mytype] in there, and then decide
141 that 'mytype' is the type of the column. It will try to find an entry of
142 'mytype' in the converters dictionary and then use the converter function found
Georg Brandl26497d92008-10-08 17:20:20 +0000143 there to return the value. The column name found in :attr:`Cursor.description`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000144 is only the first word of the column name, i. e. if you use something like
145 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
146 first blank for the column name: the column name would simply be "x".
147
148
Georg Brandle85e1ae2010-10-06 09:17:24 +0000149.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
151 Opens a connection to the SQLite database file *database*. You can use
152 ``":memory:"`` to open a database connection to a database that resides in RAM
153 instead of on disk.
154
155 When a database is accessed by multiple connections, and one of the processes
156 modifies the database, the SQLite database is locked until that transaction is
157 committed. The *timeout* parameter specifies how long the connection should wait
158 for the lock to go away until raising an exception. The default for the timeout
159 parameter is 5.0 (five seconds).
160
161 For the *isolation_level* parameter, please see the
162 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
163
164 SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
165 you want to use other types you must add support for them yourself. The
166 *detect_types* parameter and the using custom **converters** registered with the
167 module-level :func:`register_converter` function allow you to easily do that.
168
169 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
170 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
171 type detection on.
172
173 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
174 connect call. You can, however, subclass the :class:`Connection` class and make
175 :func:`connect` use your class instead by providing your class for the *factory*
176 parameter.
177
178 Consult the section :ref:`sqlite3-types` of this manual for details.
179
180 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
181 overhead. If you want to explicitly set the number of statements that are cached
182 for the connection, you can set the *cached_statements* parameter. The currently
183 implemented default is to cache 100 statements.
184
185
186.. function:: register_converter(typename, callable)
187
188 Registers a callable to convert a bytestring from the database into a custom
189 Python type. The callable will be invoked for all database values that are of
190 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
191 function for how the type detection works. Note that the case of *typename* and
192 the name of the type in your query must match!
193
194
195.. function:: register_adapter(type, callable)
196
197 Registers a callable to convert the custom Python type *type* into one of
198 SQLite's supported types. The callable *callable* accepts as single parameter
199 the Python value, and must return a value of the following types: int, long,
200 float, str (UTF-8 encoded), unicode or buffer.
201
202
203.. function:: complete_statement(sql)
204
205 Returns :const:`True` if the string *sql* contains one or more complete SQL
206 statements terminated by semicolons. It does not verify that the SQL is
207 syntactically correct, only that there are no unclosed string literals and the
208 statement is terminated by a semicolon.
209
210 This can be used to build a shell for SQLite, as in the following example:
211
212
213 .. literalinclude:: ../includes/sqlite3/complete_statement.py
214
215
216.. function:: enable_callback_tracebacks(flag)
217
218 By default you will not get any tracebacks in user-defined functions,
219 aggregates, converters, authorizer callbacks etc. If you want to debug them, you
220 can call this function with *flag* as True. Afterwards, you will get tracebacks
221 from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
222 again.
223
224
225.. _sqlite3-connection-objects:
226
227Connection Objects
228------------------
229
Georg Brandl26497d92008-10-08 17:20:20 +0000230.. class:: Connection
231
232 A SQLite database connection has the following attributes and methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000233
R David Murray95d7cdf2012-09-30 21:04:46 -0400234 .. attribute:: isolation_level
Georg Brandl8ec7f652007-08-15 14:28:01 +0000235
R David Murray95d7cdf2012-09-30 21:04:46 -0400236 Get or set the current isolation level. :const:`None` for autocommit mode or
237 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
238 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000239
240
R David Murray95d7cdf2012-09-30 21:04:46 -0400241 .. method:: cursor([cursorClass])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000242
R David Murray95d7cdf2012-09-30 21:04:46 -0400243 The cursor method accepts a single optional parameter *cursorClass*. If
244 supplied, this must be a custom cursor class that extends
245 :class:`sqlite3.Cursor`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246
R David Murray95d7cdf2012-09-30 21:04:46 -0400247 .. method:: commit()
Gerhard Häring41309302008-03-29 01:27:37 +0000248
R David Murray95d7cdf2012-09-30 21:04:46 -0400249 This method commits the current transaction. If you don't call this method,
250 anything you did since the last call to ``commit()`` is not visible from
251 other database connections. If you wonder why you don't see the data you've
252 written to the database, please check you didn't forget to call this method.
Gerhard Häring41309302008-03-29 01:27:37 +0000253
R David Murray95d7cdf2012-09-30 21:04:46 -0400254 .. method:: rollback()
Gerhard Häring41309302008-03-29 01:27:37 +0000255
R David Murray95d7cdf2012-09-30 21:04:46 -0400256 This method rolls back any changes to the database since the last call to
257 :meth:`commit`.
Gerhard Häring41309302008-03-29 01:27:37 +0000258
R David Murray95d7cdf2012-09-30 21:04:46 -0400259 .. method:: close()
Gerhard Häring41309302008-03-29 01:27:37 +0000260
R David Murray95d7cdf2012-09-30 21:04:46 -0400261 This closes the database connection. Note that this does not automatically
262 call :meth:`commit`. If you just close your database connection without
263 calling :meth:`commit` first, your changes will be lost!
Gerhard Häring41309302008-03-29 01:27:37 +0000264
R David Murray95d7cdf2012-09-30 21:04:46 -0400265 .. method:: execute(sql, [parameters])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266
R David Murray95d7cdf2012-09-30 21:04:46 -0400267 This is a nonstandard shortcut that creates an intermediate cursor object by
268 calling the cursor method, then calls the cursor's :meth:`execute
269 <Cursor.execute>` method with the parameters given.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000270
271
R David Murray95d7cdf2012-09-30 21:04:46 -0400272 .. method:: executemany(sql, [parameters])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000273
R David Murray95d7cdf2012-09-30 21:04:46 -0400274 This is a nonstandard shortcut that creates an intermediate cursor object by
275 calling the cursor method, then calls the cursor's :meth:`executemany
276 <Cursor.executemany>` method with the parameters given.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277
R David Murray95d7cdf2012-09-30 21:04:46 -0400278 .. method:: executescript(sql_script)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279
R David Murray95d7cdf2012-09-30 21:04:46 -0400280 This is a nonstandard shortcut that creates an intermediate cursor object by
281 calling the cursor method, then calls the cursor's :meth:`executescript
282 <Cursor.executescript>` method with the parameters given.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
284
R David Murray95d7cdf2012-09-30 21:04:46 -0400285 .. method:: create_function(name, num_params, func)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000286
R David Murray95d7cdf2012-09-30 21:04:46 -0400287 Creates a user-defined function that you can later use from within SQL
288 statements under the function name *name*. *num_params* is the number of
289 parameters the function accepts, and *func* is a Python callable that is called
290 as the SQL function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000291
R David Murray95d7cdf2012-09-30 21:04:46 -0400292 The function can return any of the types supported by SQLite: unicode, str, int,
293 long, float, buffer and None.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000294
R David Murray95d7cdf2012-09-30 21:04:46 -0400295 Example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000296
R David Murray95d7cdf2012-09-30 21:04:46 -0400297 .. literalinclude:: ../includes/sqlite3/md5func.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000298
299
R David Murray95d7cdf2012-09-30 21:04:46 -0400300 .. method:: create_aggregate(name, num_params, aggregate_class)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000301
R David Murray95d7cdf2012-09-30 21:04:46 -0400302 Creates a user-defined aggregate function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000303
R David Murray95d7cdf2012-09-30 21:04:46 -0400304 The aggregate class must implement a ``step`` method, which accepts the number
305 of parameters *num_params*, and a ``finalize`` method which will return the
306 final result of the aggregate.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307
R David Murray95d7cdf2012-09-30 21:04:46 -0400308 The ``finalize`` method can return any of the types supported by SQLite:
309 unicode, str, int, long, float, buffer and None.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000310
R David Murray95d7cdf2012-09-30 21:04:46 -0400311 Example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000312
R David Murray95d7cdf2012-09-30 21:04:46 -0400313 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000314
315
R David Murray95d7cdf2012-09-30 21:04:46 -0400316 .. method:: create_collation(name, callable)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317
R David Murray95d7cdf2012-09-30 21:04:46 -0400318 Creates a collation with the specified *name* and *callable*. The callable will
319 be passed two string arguments. It should return -1 if the first is ordered
320 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
321 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
322 your comparisons don't affect other SQL operations.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000323
R David Murray95d7cdf2012-09-30 21:04:46 -0400324 Note that the callable will get its parameters as Python bytestrings, which will
325 normally be encoded in UTF-8.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000326
R David Murray95d7cdf2012-09-30 21:04:46 -0400327 The following example shows a custom collation that sorts "the wrong way":
Georg Brandl8ec7f652007-08-15 14:28:01 +0000328
R David Murray95d7cdf2012-09-30 21:04:46 -0400329 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000330
R David Murray95d7cdf2012-09-30 21:04:46 -0400331 To remove a collation, call ``create_collation`` with None as callable::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000332
R David Murray95d7cdf2012-09-30 21:04:46 -0400333 con.create_collation("reverse", None)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000334
335
R David Murray95d7cdf2012-09-30 21:04:46 -0400336 .. method:: interrupt()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000337
R David Murray95d7cdf2012-09-30 21:04:46 -0400338 You can call this method from a different thread to abort any queries that might
339 be executing on the connection. The query will then abort and the caller will
340 get an exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341
342
R David Murray95d7cdf2012-09-30 21:04:46 -0400343 .. method:: set_authorizer(authorizer_callback)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000344
R David Murray95d7cdf2012-09-30 21:04:46 -0400345 This routine registers a callback. The callback is invoked for each attempt to
346 access a column of a table in the database. The callback should return
347 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
348 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
349 column should be treated as a NULL value. These constants are available in the
350 :mod:`sqlite3` module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000351
R David Murray95d7cdf2012-09-30 21:04:46 -0400352 The first argument to the callback signifies what kind of operation is to be
353 authorized. The second and third argument will be arguments or :const:`None`
354 depending on the first argument. The 4th argument is the name of the database
355 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
356 inner-most trigger or view that is responsible for the access attempt or
357 :const:`None` if this access attempt is directly from input SQL code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000358
R David Murray95d7cdf2012-09-30 21:04:46 -0400359 Please consult the SQLite documentation about the possible values for the first
360 argument and the meaning of the second and third argument depending on the first
361 one. All necessary constants are available in the :mod:`sqlite3` module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000362
363
R David Murray95d7cdf2012-09-30 21:04:46 -0400364 .. method:: set_progress_handler(handler, n)
Gerhard Häring41309302008-03-29 01:27:37 +0000365
R David Murray95d7cdf2012-09-30 21:04:46 -0400366 This routine registers a callback. The callback is invoked for every *n*
367 instructions of the SQLite virtual machine. This is useful if you want to
368 get called from SQLite during long-running operations, for example to update
369 a GUI.
Gerhard Häring41309302008-03-29 01:27:37 +0000370
R David Murray95d7cdf2012-09-30 21:04:46 -0400371 If you want to clear any previously installed progress handler, call the
372 method with :const:`None` for *handler*.
Gerhard Häring41309302008-03-29 01:27:37 +0000373
R David Murray95d7cdf2012-09-30 21:04:46 -0400374 .. versionadded:: 2.6
Petri Lehtinena15a8d22012-03-01 21:28:00 +0200375
Gerhard Häring41309302008-03-29 01:27:37 +0000376
R David Murray95d7cdf2012-09-30 21:04:46 -0400377 .. method:: enable_load_extension(enabled)
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000378
R David Murray95d7cdf2012-09-30 21:04:46 -0400379 This routine allows/disallows the SQLite engine to load SQLite extensions
380 from shared libraries. SQLite extensions can define new functions,
381 aggregates or whole new virtual table implementations. One well-known
382 extension is the fulltext-search extension distributed with SQLite.
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000383
R David Murray95d7cdf2012-09-30 21:04:46 -0400384 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000385
R David Murray95d7cdf2012-09-30 21:04:46 -0400386 .. versionadded:: 2.7
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000387
R David Murray95d7cdf2012-09-30 21:04:46 -0400388 .. literalinclude:: ../includes/sqlite3/load_extension.py
Petri Lehtinena15a8d22012-03-01 21:28:00 +0200389
R David Murray95d7cdf2012-09-30 21:04:46 -0400390 .. method:: load_extension(path)
Petri Lehtinena15a8d22012-03-01 21:28:00 +0200391
R David Murray95d7cdf2012-09-30 21:04:46 -0400392 This routine loads a SQLite extension from a shared library. You have to
393 enable extension loading with :meth:`enable_load_extension` before you can
394 use this routine.
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000395
R David Murray95d7cdf2012-09-30 21:04:46 -0400396 Loadable extensions are disabled by default. See [#f1]_.
Petri Lehtinena15a8d22012-03-01 21:28:00 +0200397
R David Murray95d7cdf2012-09-30 21:04:46 -0400398 .. versionadded:: 2.7
Senthil Kumaran7bf5ba02011-06-25 20:48:21 -0700399
R David Murray95d7cdf2012-09-30 21:04:46 -0400400 .. attribute:: row_factory
Georg Brandl8ec7f652007-08-15 14:28:01 +0000401
R David Murray95d7cdf2012-09-30 21:04:46 -0400402 You can change this attribute to a callable that accepts the cursor and the
403 original row as a tuple and will return the real result row. This way, you can
404 implement more advanced ways of returning results, such as returning an object
405 that can also access columns by name.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000406
R David Murray95d7cdf2012-09-30 21:04:46 -0400407 Example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000408
R David Murray95d7cdf2012-09-30 21:04:46 -0400409 .. literalinclude:: ../includes/sqlite3/row_factory.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000410
R David Murray95d7cdf2012-09-30 21:04:46 -0400411 If returning a tuple doesn't suffice and you want name-based access to
412 columns, you should consider setting :attr:`row_factory` to the
413 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
414 index-based and case-insensitive name-based access to columns with almost no
415 memory overhead. It will probably be better than your own custom
416 dictionary-based approach or even a db_row based solution.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000417
R David Murray95d7cdf2012-09-30 21:04:46 -0400418 .. XXX what's a db_row-based solution?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000419
420
R David Murray95d7cdf2012-09-30 21:04:46 -0400421 .. attribute:: text_factory
Georg Brandl8ec7f652007-08-15 14:28:01 +0000422
R David Murray95d7cdf2012-09-30 21:04:46 -0400423 Using this attribute you can control what objects are returned for the ``TEXT``
424 data type. By default, this attribute is set to :class:`unicode` and the
425 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
426 return bytestrings instead, you can set it to :class:`str`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000427
R David Murray95d7cdf2012-09-30 21:04:46 -0400428 For efficiency reasons, there's also a way to return Unicode objects only for
429 non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to
430 :const:`sqlite3.OptimizedUnicode`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000431
R David Murray95d7cdf2012-09-30 21:04:46 -0400432 You can also set it to any other callable that accepts a single bytestring
433 parameter and returns the resulting object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000434
R David Murray95d7cdf2012-09-30 21:04:46 -0400435 See the following example code for illustration:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000436
R David Murray95d7cdf2012-09-30 21:04:46 -0400437 .. literalinclude:: ../includes/sqlite3/text_factory.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000438
439
R David Murray95d7cdf2012-09-30 21:04:46 -0400440 .. attribute:: total_changes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000441
R David Murray95d7cdf2012-09-30 21:04:46 -0400442 Returns the total number of database rows that have been modified, inserted, or
443 deleted since the database connection was opened.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000444
445
R David Murray95d7cdf2012-09-30 21:04:46 -0400446 .. attribute:: iterdump
Gregory P. Smithb9803422008-03-28 08:32:09 +0000447
R David Murray95d7cdf2012-09-30 21:04:46 -0400448 Returns an iterator to dump the database in an SQL text format. Useful when
449 saving an in-memory database for later restoration. This function provides
450 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
451 shell.
Gregory P. Smithb9803422008-03-28 08:32:09 +0000452
R David Murray95d7cdf2012-09-30 21:04:46 -0400453 .. versionadded:: 2.6
Gregory P. Smithb9803422008-03-28 08:32:09 +0000454
R David Murray95d7cdf2012-09-30 21:04:46 -0400455 Example::
Gregory P. Smithb9803422008-03-28 08:32:09 +0000456
R David Murray95d7cdf2012-09-30 21:04:46 -0400457 # Convert file existing_db.db to SQL dump file dump.sql
458 import sqlite3, os
Gregory P. Smithb9803422008-03-28 08:32:09 +0000459
R David Murray95d7cdf2012-09-30 21:04:46 -0400460 con = sqlite3.connect('existing_db.db')
461 with open('dump.sql', 'w') as f:
462 for line in con.iterdump():
463 f.write('%s\n' % line)
Gregory P. Smithb9803422008-03-28 08:32:09 +0000464
465
Georg Brandl8ec7f652007-08-15 14:28:01 +0000466.. _sqlite3-cursor-objects:
467
468Cursor Objects
469--------------
470
Georg Brandl26946ec2010-11-26 07:42:15 +0000471.. class:: Cursor
Georg Brandl8ec7f652007-08-15 14:28:01 +0000472
Georg Brandl26946ec2010-11-26 07:42:15 +0000473 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000474
R David Murray95d7cdf2012-09-30 21:04:46 -0400475 .. method:: execute(sql, [parameters])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000476
R David Murray95d7cdf2012-09-30 21:04:46 -0400477 Executes an SQL statement. The SQL statement may be parameterized (i. e.
478 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
479 kinds of placeholders: question marks (qmark style) and named placeholders
480 (named style).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000481
R David Murray95d7cdf2012-09-30 21:04:46 -0400482 Here's an example of both styles:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000483
R David Murray95d7cdf2012-09-30 21:04:46 -0400484 .. literalinclude:: ../includes/sqlite3/execute_1.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000485
R David Murray95d7cdf2012-09-30 21:04:46 -0400486 :meth:`execute` will only execute a single SQL statement. If you try to execute
487 more than one statement with it, it will raise a Warning. Use
488 :meth:`executescript` if you want to execute multiple SQL statements with one
489 call.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000490
491
R David Murray95d7cdf2012-09-30 21:04:46 -0400492 .. method:: executemany(sql, seq_of_parameters)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000493
R David Murray95d7cdf2012-09-30 21:04:46 -0400494 Executes an SQL command against all parameter sequences or mappings found in
495 the sequence *sql*. The :mod:`sqlite3` module also allows using an
496 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000497
R David Murray95d7cdf2012-09-30 21:04:46 -0400498 .. literalinclude:: ../includes/sqlite3/executemany_1.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000499
R David Murray95d7cdf2012-09-30 21:04:46 -0400500 Here's a shorter example using a :term:`generator`:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000501
R David Murray95d7cdf2012-09-30 21:04:46 -0400502 .. literalinclude:: ../includes/sqlite3/executemany_2.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000503
504
R David Murray95d7cdf2012-09-30 21:04:46 -0400505 .. method:: executescript(sql_script)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000506
R David Murray95d7cdf2012-09-30 21:04:46 -0400507 This is a nonstandard convenience method for executing multiple SQL statements
508 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
509 gets as a parameter.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000510
R David Murray95d7cdf2012-09-30 21:04:46 -0400511 *sql_script* can be a bytestring or a Unicode string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000512
R David Murray95d7cdf2012-09-30 21:04:46 -0400513 Example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000514
R David Murray95d7cdf2012-09-30 21:04:46 -0400515 .. literalinclude:: ../includes/sqlite3/executescript.py
Georg Brandl8ec7f652007-08-15 14:28:01 +0000516
517
R David Murray95d7cdf2012-09-30 21:04:46 -0400518 .. method:: fetchone()
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000519
R David Murray95d7cdf2012-09-30 21:04:46 -0400520 Fetches the next row of a query result set, returning a single sequence,
521 or :const:`None` when no more data is available.
Georg Brandlf558d2e2008-01-19 20:53:07 +0000522
523
R David Murray95d7cdf2012-09-30 21:04:46 -0400524 .. method:: fetchmany([size=cursor.arraysize])
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000525
R David Murray95d7cdf2012-09-30 21:04:46 -0400526 Fetches the next set of rows of a query result, returning a list. An empty
527 list is returned when no more rows are available.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000528
R David Murray95d7cdf2012-09-30 21:04:46 -0400529 The number of rows to fetch per call is specified by the *size* parameter.
530 If it is not given, the cursor's arraysize determines the number of rows
531 to be fetched. The method should try to fetch as many rows as indicated by
532 the size parameter. If this is not possible due to the specified number of
533 rows not being available, fewer rows may be returned.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000534
R David Murray95d7cdf2012-09-30 21:04:46 -0400535 Note there are performance considerations involved with the *size* parameter.
536 For optimal performance, it is usually best to use the arraysize attribute.
537 If the *size* parameter is used, then it is best for it to retain the same
538 value from one :meth:`fetchmany` call to the next.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000539
R David Murray95d7cdf2012-09-30 21:04:46 -0400540 .. method:: fetchall()
Georg Brandlf558d2e2008-01-19 20:53:07 +0000541
R David Murray95d7cdf2012-09-30 21:04:46 -0400542 Fetches all (remaining) rows of a query result, returning a list. Note that
543 the cursor's arraysize attribute can affect the performance of this operation.
544 An empty list is returned when no rows are available.
Georg Brandlf558d2e2008-01-19 20:53:07 +0000545
546
R David Murray95d7cdf2012-09-30 21:04:46 -0400547 .. attribute:: rowcount
Georg Brandl8ec7f652007-08-15 14:28:01 +0000548
R David Murray95d7cdf2012-09-30 21:04:46 -0400549 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
550 attribute, the database engine's own support for the determination of "rows
551 affected"/"rows selected" is quirky.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000552
R David Murray95d7cdf2012-09-30 21:04:46 -0400553 For :meth:`executemany` statements, the number of modifications are summed up
554 into :attr:`rowcount`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000555
R David Murray95d7cdf2012-09-30 21:04:46 -0400556 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
557 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
558 last operation is not determinable by the interface". This includes ``SELECT``
559 statements because we cannot determine the number of rows a query produced
560 until all rows were fetched.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000561
R David Murray95d7cdf2012-09-30 21:04:46 -0400562 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
563 you make a ``DELETE FROM table`` without any condition.
Georg Brandl891f1d32007-08-23 20:40:01 +0000564
R David Murray95d7cdf2012-09-30 21:04:46 -0400565 .. attribute:: lastrowid
Gerhard Häringc15317e2008-03-29 19:11:52 +0000566
R David Murray95d7cdf2012-09-30 21:04:46 -0400567 This read-only attribute provides the rowid of the last modified row. It is
568 only set if you issued a ``INSERT`` statement using the :meth:`execute`
569 method. For operations other than ``INSERT`` or when :meth:`executemany` is
570 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000571
R David Murray95d7cdf2012-09-30 21:04:46 -0400572 .. attribute:: description
Georg Brandl26497d92008-10-08 17:20:20 +0000573
R David Murray95d7cdf2012-09-30 21:04:46 -0400574 This read-only attribute provides the column names of the last query. To
575 remain compatible with the Python DB API, it returns a 7-tuple for each
576 column where the last six items of each tuple are :const:`None`.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000577
R David Murray95d7cdf2012-09-30 21:04:46 -0400578 It is set for ``SELECT`` statements without any matching rows as well.
Georg Brandl26497d92008-10-08 17:20:20 +0000579
580.. _sqlite3-row-objects:
581
582Row Objects
583-----------
584
585.. class:: Row
586
587 A :class:`Row` instance serves as a highly optimized
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000588 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Georg Brandl26497d92008-10-08 17:20:20 +0000589 It tries to mimic a tuple in most of its features.
590
591 It supports mapping access by column name and index, iteration,
592 representation, equality testing and :func:`len`.
593
594 If two :class:`Row` objects have exactly the same columns and their
595 members are equal, they compare equal.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000596
Georg Brandl26497d92008-10-08 17:20:20 +0000597 .. versionchanged:: 2.6
598 Added iteration and equality (hashability).
599
600 .. method:: keys
601
602 This method returns a tuple of column names. Immediately after a query,
603 it is the first member of each tuple in :attr:`Cursor.description`.
604
605 .. versionadded:: 2.6
606
607Let's assume we initialize a table as in the example given above::
608
Senthil Kumarane04d2562011-07-03 10:12:59 -0700609 conn = sqlite3.connect(":memory:")
610 c = conn.cursor()
611 c.execute('''create table stocks
612 (date text, trans text, symbol text,
613 qty real, price real)''')
614 c.execute("""insert into stocks
615 values ('2006-01-05','BUY','RHAT',100,35.14)""")
616 conn.commit()
617 c.close()
Georg Brandl26497d92008-10-08 17:20:20 +0000618
619Now we plug :class:`Row` in::
620
Senthil Kumarane04d2562011-07-03 10:12:59 -0700621 >>> conn.row_factory = sqlite3.Row
622 >>> c = conn.cursor()
623 >>> c.execute('select * from stocks')
624 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
625 >>> r = c.fetchone()
626 >>> type(r)
627 <type 'sqlite3.Row'>
628 >>> r
629 (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
630 >>> len(r)
631 5
632 >>> r[2]
633 u'RHAT'
634 >>> r.keys()
635 ['date', 'trans', 'symbol', 'qty', 'price']
636 >>> r['qty']
637 100.0
Petri Lehtinena15a8d22012-03-01 21:28:00 +0200638 >>> for member in r:
639 ... print member
Senthil Kumarane04d2562011-07-03 10:12:59 -0700640 ...
641 2006-01-05
642 BUY
643 RHAT
644 100.0
645 35.14
Georg Brandl26497d92008-10-08 17:20:20 +0000646
647
Georg Brandl8ec7f652007-08-15 14:28:01 +0000648.. _sqlite3-types:
649
650SQLite and Python types
651-----------------------
652
653
654Introduction
655^^^^^^^^^^^^
656
Georg Brandl26497d92008-10-08 17:20:20 +0000657SQLite natively supports the following types: ``NULL``, ``INTEGER``,
658``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000659
660The following Python types can thus be sent to SQLite without any problem:
661
Georg Brandl26497d92008-10-08 17:20:20 +0000662+-----------------------------+-------------+
663| Python type | SQLite type |
664+=============================+=============+
665| :const:`None` | ``NULL`` |
666+-----------------------------+-------------+
667| :class:`int` | ``INTEGER`` |
668+-----------------------------+-------------+
669| :class:`long` | ``INTEGER`` |
670+-----------------------------+-------------+
671| :class:`float` | ``REAL`` |
672+-----------------------------+-------------+
673| :class:`str` (UTF8-encoded) | ``TEXT`` |
674+-----------------------------+-------------+
675| :class:`unicode` | ``TEXT`` |
676+-----------------------------+-------------+
677| :class:`buffer` | ``BLOB`` |
678+-----------------------------+-------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000679
680This is how SQLite types are converted to Python types by default:
681
Georg Brandl26497d92008-10-08 17:20:20 +0000682+-------------+----------------------------------------------+
683| SQLite type | Python type |
684+=============+==============================================+
685| ``NULL`` | :const:`None` |
686+-------------+----------------------------------------------+
687| ``INTEGER`` | :class:`int` or :class:`long`, |
688| | depending on size |
689+-------------+----------------------------------------------+
690| ``REAL`` | :class:`float` |
691+-------------+----------------------------------------------+
692| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
693| | :class:`unicode` by default |
694+-------------+----------------------------------------------+
695| ``BLOB`` | :class:`buffer` |
696+-------------+----------------------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000697
698The type system of the :mod:`sqlite3` module is extensible in two ways: you can
699store additional Python types in a SQLite database via object adaptation, and
700you can let the :mod:`sqlite3` module convert SQLite types to different Python
701types via converters.
702
703
704Using adapters to store additional Python types in SQLite databases
705^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
706
707As described before, SQLite supports only a limited set of types natively. To
708use other Python types with SQLite, you must **adapt** them to one of the
709sqlite3 module's supported types for SQLite: one of NoneType, int, long, float,
710str, unicode, buffer.
711
712The :mod:`sqlite3` module uses Python object adaptation, as described in
713:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
714
715There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
716type to one of the supported ones.
717
718
719Letting your object adapt itself
720""""""""""""""""""""""""""""""""
721
722This is a good approach if you write the class yourself. Let's suppose you have
723a class like this::
724
725 class Point(object):
726 def __init__(self, x, y):
727 self.x, self.y = x, y
728
729Now you want to store the point in a single SQLite column. First you'll have to
730choose one of the supported types first to be used for representing the point.
731Let's just use str and separate the coordinates using a semicolon. Then you need
732to give your class a method ``__conform__(self, protocol)`` which must return
733the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
734
735.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
736
737
738Registering an adapter callable
739"""""""""""""""""""""""""""""""
740
741The other possibility is to create a function that converts the type to the
742string representation and register the function with :meth:`register_adapter`.
743
744.. note::
745
Georg Brandla7395032007-10-21 12:15:05 +0000746 The type/class to adapt must be a :term:`new-style class`, i. e. it must have
Georg Brandl8ec7f652007-08-15 14:28:01 +0000747 :class:`object` as one of its bases.
748
749.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
750
751The :mod:`sqlite3` module has two default adapters for Python's built-in
752:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
753we want to store :class:`datetime.datetime` objects not in ISO representation,
754but as a Unix timestamp.
755
756.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
757
758
759Converting SQLite values to custom Python types
760^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
761
762Writing an adapter lets you send custom Python types to SQLite. But to make it
763really useful we need to make the Python to SQLite to Python roundtrip work.
764
765Enter converters.
766
767Let's go back to the :class:`Point` class. We stored the x and y coordinates
768separated via semicolons as strings in SQLite.
769
770First, we'll define a converter function that accepts the string as a parameter
771and constructs a :class:`Point` object from it.
772
773.. note::
774
775 Converter functions **always** get called with a string, no matter under which
776 data type you sent the value to SQLite.
777
Georg Brandl8ec7f652007-08-15 14:28:01 +0000778::
779
780 def convert_point(s):
781 x, y = map(float, s.split(";"))
782 return Point(x, y)
783
784Now you need to make the :mod:`sqlite3` module know that what you select from
785the database is actually a point. There are two ways of doing this:
786
787* Implicitly via the declared type
788
789* Explicitly via the column name
790
791Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
792for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
793
794The following example illustrates both approaches.
795
796.. literalinclude:: ../includes/sqlite3/converter_point.py
797
798
799Default adapters and converters
800^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
801
802There are default adapters for the date and datetime types in the datetime
803module. They will be sent as ISO dates/ISO timestamps to SQLite.
804
805The default converters are registered under the name "date" for
806:class:`datetime.date` and under the name "timestamp" for
807:class:`datetime.datetime`.
808
809This way, you can use date/timestamps from Python without any additional
810fiddling in most cases. The format of the adapters is also compatible with the
811experimental SQLite date/time functions.
812
813The following example demonstrates this.
814
815.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
816
817
818.. _sqlite3-controlling-transactions:
819
820Controlling Transactions
821------------------------
822
823By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000824Data Modification Language (DML) statement (i.e.
Georg Brandl26497d92008-10-08 17:20:20 +0000825``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
826implicitly before a non-DML, non-query statement (i. e.
827anything other than ``SELECT`` or the aforementioned).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000828
829So if you are within a transaction and issue a command like ``CREATE TABLE
830...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
831before executing that command. There are two reasons for doing that. The first
832is that some of these commands don't work within transactions. The other reason
Georg Brandl498a9b32009-05-20 18:31:14 +0000833is that sqlite3 needs to keep track of the transaction state (if a transaction
Georg Brandl8ec7f652007-08-15 14:28:01 +0000834is active or not).
835
Georg Brandl498a9b32009-05-20 18:31:14 +0000836You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000837(or none at all) via the *isolation_level* parameter to the :func:`connect`
838call, or via the :attr:`isolation_level` property of connections.
839
840If you want **autocommit mode**, then set :attr:`isolation_level` to None.
841
842Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandlb9bfea72008-11-06 10:19:11 +0000843statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
844"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl8ec7f652007-08-15 14:28:01 +0000845
Georg Brandl8ec7f652007-08-15 14:28:01 +0000846
847
Georg Brandl498a9b32009-05-20 18:31:14 +0000848Using :mod:`sqlite3` efficiently
849--------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000850
851
852Using shortcut methods
853^^^^^^^^^^^^^^^^^^^^^^
854
855Using the nonstandard :meth:`execute`, :meth:`executemany` and
856:meth:`executescript` methods of the :class:`Connection` object, your code can
857be written more concisely because you don't have to create the (often
858superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
859objects are created implicitly and these shortcut methods return the cursor
Georg Brandl26497d92008-10-08 17:20:20 +0000860objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl8ec7f652007-08-15 14:28:01 +0000861directly using only a single call on the :class:`Connection` object.
862
863.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
864
865
866Accessing columns by name instead of by index
867^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
868
Georg Brandld7d4fd72009-07-26 14:37:28 +0000869One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000870:class:`sqlite3.Row` class designed to be used as a row factory.
871
872Rows wrapped with this class can be accessed both by index (like tuples) and
873case-insensitively by name:
874
875.. literalinclude:: ../includes/sqlite3/rowclass.py
876
Gerhard Häring41309302008-03-29 01:27:37 +0000877
878Using the connection as a context manager
879^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
880
881.. versionadded:: 2.6
882
883Connection objects can be used as context managers
884that automatically commit or rollback transactions. In the event of an
885exception, the transaction is rolled back; otherwise, the transaction is
886committed:
887
888.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häring5f5c15f2010-08-06 06:14:12 +0000889
890
891Common issues
892-------------
893
894Multithreading
895^^^^^^^^^^^^^^
896
897Older SQLite versions had issues with sharing connections between threads.
898That's why the Python module disallows sharing connections and cursors between
899threads. If you still try to do so, you will get an exception at runtime.
900
901The only exception is calling the :meth:`~Connection.interrupt` method, which
902only makes sense to call from a different thread.
Senthil Kumaran7bf5ba02011-06-25 20:48:21 -0700903
904.. rubric:: Footnotes
905
906.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumarane04d2562011-07-03 10:12:59 -0700907 default, because some platforms (notably Mac OS X) have SQLite libraries
908 which are compiled without this feature. To get loadable extension support,
909 you must modify setup.py and remove the line that sets
910 SQLITE_OMIT_LOAD_EXTENSION.
Senthil Kumaran7bf5ba02011-06-25 20:48:21 -0700911