blob: ea92032b28e60051be43bbfaff881f55a368b390 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`sqlite3` --- DB-API 2.0 interface for SQLite databases
2============================================================
3
4.. module:: sqlite3
5 :synopsis: A DB-API 2.0 implementation using SQLite 3.x.
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +02006.. sectionauthor:: Gerhard Häring <gh@ghaering.de>
Georg Brandl116aa622007-08-15 14:28:22 +00007
8
Georg Brandl116aa622007-08-15 14:28:22 +00009SQLite is a C library that provides a lightweight disk-based database that
10doesn't require a separate server process and allows accessing the database
11using a nonstandard variant of the SQL query language. Some applications can use
12SQLite for internal data storage. It's also possible to prototype an
13application using SQLite and then port the code to a larger database such as
14PostgreSQL or Oracle.
15
Georg Brandl8a1e4c42009-05-25 21:13:36 +000016sqlite3 was written by Gerhard Häring and provides a SQL interface compliant
Georg Brandl116aa622007-08-15 14:28:22 +000017with the DB-API 2.0 specification described by :pep:`249`.
18
19To use the module, you must first create a :class:`Connection` object that
20represents the database. Here the data will be stored in the
21:file:`/tmp/example` file::
22
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020023 import sqlite3
Georg Brandl116aa622007-08-15 14:28:22 +000024 conn = sqlite3.connect('/tmp/example')
25
26You can also supply the special name ``:memory:`` to create a database in RAM.
27
28Once you have a :class:`Connection`, you can create a :class:`Cursor` object
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000029and call its :meth:`~Cursor.execute` method to perform SQL commands::
Georg Brandl116aa622007-08-15 14:28:22 +000030
31 c = conn.cursor()
32
33 # Create table
34 c.execute('''create table stocks
35 (date text, trans text, symbol text,
36 qty real, price real)''')
37
38 # Insert a row of data
39 c.execute("""insert into stocks
40 values ('2006-01-05','BUY','RHAT',100,35.14)""")
41
42 # Save (commit) the changes
43 conn.commit()
44
45 # We can also close the cursor if we are done with it
46 c.close()
47
48Usually your SQL operations will need to use values from Python variables. You
49shouldn't assemble your query using Python's string operations because doing so
50is insecure; it makes your program vulnerable to an SQL injection attack.
51
52Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
53wherever you want to use a value, and then provide a tuple of values as the
Georg Brandl8a1e4c42009-05-25 21:13:36 +000054second argument to the cursor's :meth:`~Cursor.execute` method. (Other database
55modules may use a different placeholder, such as ``%s`` or ``:1``.) For
56example::
Georg Brandl116aa622007-08-15 14:28:22 +000057
58 # Never do this -- insecure!
59 symbol = 'IBM'
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020060 c.execute("select * from stocks where symbol = '%s'" % symbol)
Georg Brandl116aa622007-08-15 14:28:22 +000061
62 # Do this instead
63 t = (symbol,)
64 c.execute('select * from stocks where symbol=?', t)
65
66 # Larger example
Georg Brandla971c652008-11-07 09:39:56 +000067 for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +020068 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
Georg Brandl116aa622007-08-15 14:28:22 +000069 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
Georg Brandla971c652008-11-07 09:39:56 +000070 ]:
Georg Brandl116aa622007-08-15 14:28:22 +000071 c.execute('insert into stocks values (?,?,?,?,?)', t)
72
Georg Brandl9afde1c2007-11-01 20:32:30 +000073To retrieve data after executing a SELECT statement, you can either treat the
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000074cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
75retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandl9afde1c2007-11-01 20:32:30 +000076matching rows.
Georg Brandl116aa622007-08-15 14:28:22 +000077
78This example uses the iterator form::
79
80 >>> c = conn.cursor()
81 >>> c.execute('select * from stocks order by price')
82 >>> for row in c:
Ezio Melottib5845052009-09-13 05:49:25 +000083 ... print(row)
Georg Brandl116aa622007-08-15 14:28:22 +000084 ...
Ezio Melottib5845052009-09-13 05:49:25 +000085 ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
86 ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
87 ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
88 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.0)
Georg Brandl116aa622007-08-15 14:28:22 +000089 >>>
90
91
92.. seealso::
93
Benjamin Peterson2614cda2010-03-21 22:36:19 +000094 http://code.google.com/p/pysqlite/
Georg Brandl8a1e4c42009-05-25 21:13:36 +000095 The pysqlite web page -- sqlite3 is developed externally under the name
96 "pysqlite".
Georg Brandl116aa622007-08-15 14:28:22 +000097
98 http://www.sqlite.org
Georg Brandl8a1e4c42009-05-25 21:13:36 +000099 The SQLite web page; the documentation describes the syntax and the
100 available data types for the supported SQL dialect.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102 :pep:`249` - Database API Specification 2.0
103 PEP written by Marc-André Lemburg.
104
105
106.. _sqlite3-module-contents:
107
108Module functions and constants
109------------------------------
110
111
112.. data:: PARSE_DECLTYPES
113
114 This constant is meant to be used with the *detect_types* parameter of the
115 :func:`connect` function.
116
117 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000118 column it returns. It will parse out the first word of the declared type,
119 i. e. for "integer primary key", it will parse out "integer", or for
120 "number(10)" it will parse out "number". Then for that column, it will look
121 into the converters dictionary and use the converter function registered for
122 that type there.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124
125.. data:: PARSE_COLNAMES
126
127 This constant is meant to be used with the *detect_types* parameter of the
128 :func:`connect` function.
129
130 Setting this makes the SQLite interface parse the column name for each column it
131 returns. It will look for a string formed [mytype] in there, and then decide
132 that 'mytype' is the type of the column. It will try to find an entry of
133 'mytype' in the converters dictionary and then use the converter function found
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000134 there to return the value. The column name found in :attr:`Cursor.description`
Georg Brandl116aa622007-08-15 14:28:22 +0000135 is only the first word of the column name, i. e. if you use something like
136 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
137 first blank for the column name: the column name would simply be "x".
138
139
Georg Brandl1c616a52010-07-10 12:01:34 +0000140.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
Georg Brandl116aa622007-08-15 14:28:22 +0000141
142 Opens a connection to the SQLite database file *database*. You can use
143 ``":memory:"`` to open a database connection to a database that resides in RAM
144 instead of on disk.
145
146 When a database is accessed by multiple connections, and one of the processes
147 modifies the database, the SQLite database is locked until that transaction is
148 committed. The *timeout* parameter specifies how long the connection should wait
149 for the lock to go away until raising an exception. The default for the timeout
150 parameter is 5.0 (five seconds).
151
152 For the *isolation_level* parameter, please see the
153 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
154
155 SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
156 you want to use other types you must add support for them yourself. The
157 *detect_types* parameter and the using custom **converters** registered with the
158 module-level :func:`register_converter` function allow you to easily do that.
159
160 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
161 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
162 type detection on.
163
164 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
165 connect call. You can, however, subclass the :class:`Connection` class and make
166 :func:`connect` use your class instead by providing your class for the *factory*
167 parameter.
168
169 Consult the section :ref:`sqlite3-types` of this manual for details.
170
171 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
172 overhead. If you want to explicitly set the number of statements that are cached
173 for the connection, you can set the *cached_statements* parameter. The currently
174 implemented default is to cache 100 statements.
175
176
177.. function:: register_converter(typename, callable)
178
179 Registers a callable to convert a bytestring from the database into a custom
180 Python type. The callable will be invoked for all database values that are of
181 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
182 function for how the type detection works. Note that the case of *typename* and
183 the name of the type in your query must match!
184
185
186.. function:: register_adapter(type, callable)
187
188 Registers a callable to convert the custom Python type *type* into one of
189 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000190 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000191 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193
194.. function:: complete_statement(sql)
195
196 Returns :const:`True` if the string *sql* contains one or more complete SQL
197 statements terminated by semicolons. It does not verify that the SQL is
198 syntactically correct, only that there are no unclosed string literals and the
199 statement is terminated by a semicolon.
200
201 This can be used to build a shell for SQLite, as in the following example:
202
203
204 .. literalinclude:: ../includes/sqlite3/complete_statement.py
205
206
207.. function:: enable_callback_tracebacks(flag)
208
209 By default you will not get any tracebacks in user-defined functions,
210 aggregates, converters, authorizer callbacks etc. If you want to debug them, you
211 can call this function with *flag* as True. Afterwards, you will get tracebacks
212 from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
213 again.
214
215
216.. _sqlite3-connection-objects:
217
218Connection Objects
219------------------
220
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000221.. class:: Connection
222
223 A SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225.. attribute:: Connection.isolation_level
226
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000227 Get or set the current isolation level. :const:`None` for autocommit mode or
228 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
Georg Brandl116aa622007-08-15 14:28:22 +0000229 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
230
R. David Murrayd35251d2010-06-01 01:32:12 +0000231.. attribute:: Connection.in_transaction
232
Benjamin Peterson5c5eb362010-06-06 02:40:38 +0000233 :const:`True` if a transaction is active (there are uncommitted changes),
R. David Murrayd35251d2010-06-01 01:32:12 +0000234 :const:`False` otherwise. Read-only attribute.
235
Georg Brandl67b21b72010-08-17 15:07:14 +0000236 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238.. method:: Connection.cursor([cursorClass])
239
240 The cursor method accepts a single optional parameter *cursorClass*. If
241 supplied, this must be a custom cursor class that extends
242 :class:`sqlite3.Cursor`.
243
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000244.. method:: Connection.commit()
245
246 This method commits the current transaction. If you don't call this method,
Ezio Melottie130a522011-10-19 10:58:56 +0300247 anything you did since the last call to ``commit()`` is not visible from
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000248 other database connections. If you wonder why you don't see the data you've
249 written to the database, please check you didn't forget to call this method.
250
251.. method:: Connection.rollback()
252
253 This method rolls back any changes to the database since the last call to
254 :meth:`commit`.
255
256.. method:: Connection.close()
257
258 This closes the database connection. Note that this does not automatically
259 call :meth:`commit`. If you just close your database connection without
260 calling :meth:`commit` first, your changes will be lost!
261
Georg Brandl116aa622007-08-15 14:28:22 +0000262.. method:: Connection.execute(sql, [parameters])
263
264 This is a nonstandard shortcut that creates an intermediate cursor object by
Georg Brandl96115fb22010-10-17 09:33:24 +0000265 calling the cursor method, then calls the cursor's :meth:`execute
266 <Cursor.execute>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268
269.. method:: Connection.executemany(sql, [parameters])
270
271 This is a nonstandard shortcut that creates an intermediate cursor object by
Georg Brandl96115fb22010-10-17 09:33:24 +0000272 calling the cursor method, then calls the cursor's :meth:`executemany
273 <Cursor.executemany>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Georg Brandl116aa622007-08-15 14:28:22 +0000275.. method:: Connection.executescript(sql_script)
276
277 This is a nonstandard shortcut that creates an intermediate cursor object by
Georg Brandl96115fb22010-10-17 09:33:24 +0000278 calling the cursor method, then calls the cursor's :meth:`executescript
279 <Cursor.executescript>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281
282.. method:: Connection.create_function(name, num_params, func)
283
284 Creates a user-defined function that you can later use from within SQL
285 statements under the function name *name*. *num_params* is the number of
286 parameters the function accepts, and *func* is a Python callable that is called
287 as the SQL function.
288
Georg Brandlf6945182008-02-01 11:56:49 +0000289 The function can return any of the types supported by SQLite: bytes, str, int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000290 float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000291
292 Example:
293
294 .. literalinclude:: ../includes/sqlite3/md5func.py
295
296
297.. method:: Connection.create_aggregate(name, num_params, aggregate_class)
298
299 Creates a user-defined aggregate function.
300
301 The aggregate class must implement a ``step`` method, which accepts the number
302 of parameters *num_params*, and a ``finalize`` method which will return the
303 final result of the aggregate.
304
305 The ``finalize`` method can return any of the types supported by SQLite:
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000306 bytes, str, int, float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308 Example:
309
310 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
311
312
313.. method:: Connection.create_collation(name, callable)
314
315 Creates a collation with the specified *name* and *callable*. The callable will
316 be passed two string arguments. It should return -1 if the first is ordered
317 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
318 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
319 your comparisons don't affect other SQL operations.
320
321 Note that the callable will get its parameters as Python bytestrings, which will
322 normally be encoded in UTF-8.
323
324 The following example shows a custom collation that sorts "the wrong way":
325
326 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
327
328 To remove a collation, call ``create_collation`` with None as callable::
329
330 con.create_collation("reverse", None)
331
332
333.. method:: Connection.interrupt()
334
335 You can call this method from a different thread to abort any queries that might
336 be executing on the connection. The query will then abort and the caller will
337 get an exception.
338
339
340.. method:: Connection.set_authorizer(authorizer_callback)
341
342 This routine registers a callback. The callback is invoked for each attempt to
343 access a column of a table in the database. The callback should return
344 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
345 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
346 column should be treated as a NULL value. These constants are available in the
347 :mod:`sqlite3` module.
348
349 The first argument to the callback signifies what kind of operation is to be
350 authorized. The second and third argument will be arguments or :const:`None`
351 depending on the first argument. The 4th argument is the name of the database
352 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
353 inner-most trigger or view that is responsible for the access attempt or
354 :const:`None` if this access attempt is directly from input SQL code.
355
356 Please consult the SQLite documentation about the possible values for the first
357 argument and the meaning of the second and third argument depending on the first
358 one. All necessary constants are available in the :mod:`sqlite3` module.
359
360
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000361.. method:: Connection.set_progress_handler(handler, n)
362
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000363 This routine registers a callback. The callback is invoked for every *n*
364 instructions of the SQLite virtual machine. This is useful if you want to
365 get called from SQLite during long-running operations, for example to update
366 a GUI.
367
368 If you want to clear any previously installed progress handler, call the
369 method with :const:`None` for *handler*.
370
371
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200372.. method:: Connection.set_trace_callback(trace_callback)
373
374 Registers *trace_callback* to be called for each SQL statement that is
375 actually executed by the SQLite backend.
376
377 The only argument passed to the callback is the statement (as string) that
378 is being executed. The return value of the callback is ignored. Note that
379 the backend does not only run statements passed to the :meth:`Cursor.execute`
380 methods. Other sources include the transaction management of the Python
381 module and the execution of triggers defined in the current database.
382
383 Passing :const:`None` as *trace_callback* will disable the trace callback.
384
385 .. versionadded:: 3.3
386
387
Gerhard Häringf9cee222010-03-05 15:20:03 +0000388.. method:: Connection.enable_load_extension(enabled)
389
Gerhard Häringf9cee222010-03-05 15:20:03 +0000390 This routine allows/disallows the SQLite engine to load SQLite extensions
391 from shared libraries. SQLite extensions can define new functions,
Georg Brandl96115fb22010-10-17 09:33:24 +0000392 aggregates or whole new virtual table implementations. One well-known
Gerhard Häringf9cee222010-03-05 15:20:03 +0000393 extension is the fulltext-search extension distributed with SQLite.
394
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200395 Loadable extensions are disabled by default. See [#f1]_.
396
Georg Brandl67b21b72010-08-17 15:07:14 +0000397 .. versionadded:: 3.2
398
Gerhard Häringf9cee222010-03-05 15:20:03 +0000399 .. literalinclude:: ../includes/sqlite3/load_extension.py
400
401.. method:: Connection.load_extension(path)
402
Georg Brandl96115fb22010-10-17 09:33:24 +0000403 This routine loads a SQLite extension from a shared library. You have to
404 enable extension loading with :meth:`enable_load_extension` before you can
405 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000406
Georg Brandl96115fb22010-10-17 09:33:24 +0000407 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringe0941c52010-10-03 21:47:06 +0000408
Petri Lehtinen4d2bfb52012-03-01 21:18:34 +0200409 .. versionadded:: 3.2
410
Georg Brandl116aa622007-08-15 14:28:22 +0000411.. attribute:: Connection.row_factory
412
413 You can change this attribute to a callable that accepts the cursor and the
414 original row as a tuple and will return the real result row. This way, you can
415 implement more advanced ways of returning results, such as returning an object
416 that can also access columns by name.
417
418 Example:
419
420 .. literalinclude:: ../includes/sqlite3/row_factory.py
421
422 If returning a tuple doesn't suffice and you want name-based access to
423 columns, you should consider setting :attr:`row_factory` to the
424 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
425 index-based and case-insensitive name-based access to columns with almost no
426 memory overhead. It will probably be better than your own custom
427 dictionary-based approach or even a db_row based solution.
428
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000429 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431
432.. attribute:: Connection.text_factory
433
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000434 Using this attribute you can control what objects are returned for the ``TEXT``
435 data type. By default, this attribute is set to :class:`str` and the
436 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
Georg Brandlf6945182008-02-01 11:56:49 +0000437 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000438
Georg Brandl116aa622007-08-15 14:28:22 +0000439 You can also set it to any other callable that accepts a single bytestring
440 parameter and returns the resulting object.
441
442 See the following example code for illustration:
443
444 .. literalinclude:: ../includes/sqlite3/text_factory.py
445
446
447.. attribute:: Connection.total_changes
448
449 Returns the total number of database rows that have been modified, inserted, or
450 deleted since the database connection was opened.
451
452
Christian Heimesbbe741d2008-03-28 10:53:29 +0000453.. attribute:: Connection.iterdump
454
455 Returns an iterator to dump the database in an SQL text format. Useful when
456 saving an in-memory database for later restoration. This function provides
457 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
458 shell.
459
Christian Heimesbbe741d2008-03-28 10:53:29 +0000460 Example::
461
462 # Convert file existing_db.db to SQL dump file dump.sql
463 import sqlite3, os
464
465 con = sqlite3.connect('existing_db.db')
Georg Brandla971c652008-11-07 09:39:56 +0000466 with open('dump.sql', 'w') as f:
467 for line in con.iterdump():
468 f.write('%s\n' % line)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000469
470
Georg Brandl116aa622007-08-15 14:28:22 +0000471.. _sqlite3-cursor-objects:
472
473Cursor Objects
474--------------
475
Georg Brandl96115fb22010-10-17 09:33:24 +0000476.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000477
Georg Brandl96115fb22010-10-17 09:33:24 +0000478 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000479
480.. method:: Cursor.execute(sql, [parameters])
481
Christian Heimesfdab48e2008-01-20 09:06:41 +0000482 Executes an SQL statement. The SQL statement may be parametrized (i. e.
Georg Brandl116aa622007-08-15 14:28:22 +0000483 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
484 kinds of placeholders: question marks (qmark style) and named placeholders
485 (named style).
486
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200487 Here's an example of both styles:
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489 .. literalinclude:: ../includes/sqlite3/execute_1.py
490
Georg Brandl116aa622007-08-15 14:28:22 +0000491 :meth:`execute` will only execute a single SQL statement. If you try to execute
492 more than one statement with it, it will raise a Warning. Use
493 :meth:`executescript` if you want to execute multiple SQL statements with one
494 call.
495
496
497.. method:: Cursor.executemany(sql, seq_of_parameters)
498
Christian Heimesfdab48e2008-01-20 09:06:41 +0000499 Executes an SQL command against all parameter sequences or mappings found in
Georg Brandl9afde1c2007-11-01 20:32:30 +0000500 the sequence *sql*. The :mod:`sqlite3` module also allows using an
501 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000502
503 .. literalinclude:: ../includes/sqlite3/executemany_1.py
504
Georg Brandl9afde1c2007-11-01 20:32:30 +0000505 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000506
507 .. literalinclude:: ../includes/sqlite3/executemany_2.py
508
509
510.. method:: Cursor.executescript(sql_script)
511
512 This is a nonstandard convenience method for executing multiple SQL statements
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000513 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
Georg Brandl116aa622007-08-15 14:28:22 +0000514 gets as a parameter.
515
Georg Brandlf6945182008-02-01 11:56:49 +0000516 *sql_script* can be an instance of :class:`str` or :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000517
518 Example:
519
520 .. literalinclude:: ../includes/sqlite3/executescript.py
521
522
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000523.. method:: Cursor.fetchone()
524
Christian Heimesfdab48e2008-01-20 09:06:41 +0000525 Fetches the next row of a query result set, returning a single sequence,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000526 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000527
528
529.. method:: Cursor.fetchmany([size=cursor.arraysize])
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000530
Christian Heimesfdab48e2008-01-20 09:06:41 +0000531 Fetches the next set of rows of a query result, returning a list. An empty
532 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000533
Christian Heimesfdab48e2008-01-20 09:06:41 +0000534 The number of rows to fetch per call is specified by the *size* parameter.
535 If it is not given, the cursor's arraysize determines the number of rows
536 to be fetched. The method should try to fetch as many rows as indicated by
537 the size parameter. If this is not possible due to the specified number of
538 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000539
Christian Heimesfdab48e2008-01-20 09:06:41 +0000540 Note there are performance considerations involved with the *size* parameter.
541 For optimal performance, it is usually best to use the arraysize attribute.
542 If the *size* parameter is used, then it is best for it to retain the same
543 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000544
545.. method:: Cursor.fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000546
547 Fetches all (remaining) rows of a query result, returning a list. Note that
548 the cursor's arraysize attribute can affect the performance of this operation.
549 An empty list is returned when no rows are available.
550
551
Georg Brandl116aa622007-08-15 14:28:22 +0000552.. attribute:: Cursor.rowcount
553
554 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
555 attribute, the database engine's own support for the determination of "rows
556 affected"/"rows selected" is quirky.
557
Georg Brandl116aa622007-08-15 14:28:22 +0000558 For :meth:`executemany` statements, the number of modifications are summed up
559 into :attr:`rowcount`.
560
561 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000562 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
Petri Lehtinenb3890222012-02-16 21:39:03 +0200563 last operation is not determinable by the interface". This includes ``SELECT``
564 statements because we cannot determine the number of rows a query produced
565 until all rows were fetched.
Georg Brandl116aa622007-08-15 14:28:22 +0000566
Petri Lehtinenb3890222012-02-16 21:39:03 +0200567 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
568 you make a ``DELETE FROM table`` without any condition.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000569
Gerhard Häringd3372792008-03-29 19:13:55 +0000570.. attribute:: Cursor.lastrowid
571
572 This read-only attribute provides the rowid of the last modified row. It is
573 only set if you issued a ``INSERT`` statement using the :meth:`execute`
574 method. For operations other than ``INSERT`` or when :meth:`executemany` is
575 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl116aa622007-08-15 14:28:22 +0000576
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000577.. attribute:: Cursor.description
578
579 This read-only attribute provides the column names of the last query. To
580 remain compatible with the Python DB API, it returns a 7-tuple for each
Georg Brandl48310cd2009-01-03 21:18:54 +0000581 column where the last six items of each tuple are :const:`None`.
582
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000583 It is set for ``SELECT`` statements without any matching rows as well.
584
585.. _sqlite3-row-objects:
586
587Row Objects
588-----------
589
590.. class:: Row
591
592 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000593 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000594 It tries to mimic a tuple in most of its features.
595
596 It supports mapping access by column name and index, iteration,
597 representation, equality testing and :func:`len`.
598
599 If two :class:`Row` objects have exactly the same columns and their
600 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000601
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000602 .. method:: keys
603
604 This method returns a tuple of column names. Immediately after a query,
605 it is the first member of each tuple in :attr:`Cursor.description`.
606
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000607Let's assume we initialize a table as in the example given above::
608
Senthil Kumaran946eb862011-07-03 10:17:22 -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()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000618
619Now we plug :class:`Row` in::
620
Senthil Kumaran946eb862011-07-03 10:17:22 -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 <class 'sqlite3.Row'>
628 >>> tuple(r)
629 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
630 >>> len(r)
631 5
632 >>> r[2]
633 'RHAT'
634 >>> r.keys()
635 ['date', 'trans', 'symbol', 'qty', 'price']
636 >>> r['qty']
637 100.0
638 >>> for member in r:
639 ... print(member)
640 ...
641 2006-01-05
642 BUY
643 RHAT
644 100.0
645 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000646
647
Georg Brandl116aa622007-08-15 14:28:22 +0000648.. _sqlite3-types:
649
650SQLite and Python types
651-----------------------
652
653
654Introduction
655^^^^^^^^^^^^
656
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000657SQLite natively supports the following types: ``NULL``, ``INTEGER``,
658``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000659
660The following Python types can thus be sent to SQLite without any problem:
661
Georg Brandlf6945182008-02-01 11:56:49 +0000662+-------------------------------+-------------+
663| Python type | SQLite type |
664+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000665| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000666+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000667| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000668+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000669| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000670+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000671| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000672+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000673| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000674+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000675
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000676
Georg Brandl116aa622007-08-15 14:28:22 +0000677This is how SQLite types are converted to Python types by default:
678
679+-------------+---------------------------------------------+
680| SQLite type | Python type |
681+=============+=============================================+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000682| ``NULL`` | :const:`None` |
Georg Brandl116aa622007-08-15 14:28:22 +0000683+-------------+---------------------------------------------+
Ezio Melottib5845052009-09-13 05:49:25 +0000684| ``INTEGER`` | :class:`int` |
Georg Brandl116aa622007-08-15 14:28:22 +0000685+-------------+---------------------------------------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000686| ``REAL`` | :class:`float` |
Georg Brandl116aa622007-08-15 14:28:22 +0000687+-------------+---------------------------------------------+
Georg Brandlf6945182008-02-01 11:56:49 +0000688| ``TEXT`` | depends on text_factory, str by default |
Georg Brandl116aa622007-08-15 14:28:22 +0000689+-------------+---------------------------------------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000690| ``BLOB`` | :class:`bytes` |
Georg Brandl116aa622007-08-15 14:28:22 +0000691+-------------+---------------------------------------------+
692
693The type system of the :mod:`sqlite3` module is extensible in two ways: you can
694store additional Python types in a SQLite database via object adaptation, and
695you can let the :mod:`sqlite3` module convert SQLite types to different Python
696types via converters.
697
698
699Using adapters to store additional Python types in SQLite databases
700^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
701
702As described before, SQLite supports only a limited set of types natively. To
703use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000704sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000705str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000706
707The :mod:`sqlite3` module uses Python object adaptation, as described in
708:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
709
710There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
711type to one of the supported ones.
712
713
714Letting your object adapt itself
715""""""""""""""""""""""""""""""""
716
717This is a good approach if you write the class yourself. Let's suppose you have
718a class like this::
719
Éric Araujo28053fb2010-11-22 03:09:19 +0000720 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000721 def __init__(self, x, y):
722 self.x, self.y = x, y
723
724Now you want to store the point in a single SQLite column. First you'll have to
725choose one of the supported types first to be used for representing the point.
726Let's just use str and separate the coordinates using a semicolon. Then you need
727to give your class a method ``__conform__(self, protocol)`` which must return
728the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
729
730.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
731
732
733Registering an adapter callable
734"""""""""""""""""""""""""""""""
735
736The other possibility is to create a function that converts the type to the
737string representation and register the function with :meth:`register_adapter`.
738
Georg Brandl116aa622007-08-15 14:28:22 +0000739.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
740
741The :mod:`sqlite3` module has two default adapters for Python's built-in
742:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
743we want to store :class:`datetime.datetime` objects not in ISO representation,
744but as a Unix timestamp.
745
746.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
747
748
749Converting SQLite values to custom Python types
750^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
751
752Writing an adapter lets you send custom Python types to SQLite. But to make it
753really useful we need to make the Python to SQLite to Python roundtrip work.
754
755Enter converters.
756
757Let's go back to the :class:`Point` class. We stored the x and y coordinates
758separated via semicolons as strings in SQLite.
759
760First, we'll define a converter function that accepts the string as a parameter
761and constructs a :class:`Point` object from it.
762
763.. note::
764
765 Converter functions **always** get called with a string, no matter under which
766 data type you sent the value to SQLite.
767
Georg Brandl116aa622007-08-15 14:28:22 +0000768::
769
770 def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +0200771 x, y = map(float, s.split(b";"))
Georg Brandl116aa622007-08-15 14:28:22 +0000772 return Point(x, y)
773
774Now you need to make the :mod:`sqlite3` module know that what you select from
775the database is actually a point. There are two ways of doing this:
776
777* Implicitly via the declared type
778
779* Explicitly via the column name
780
781Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
782for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
783
784The following example illustrates both approaches.
785
786.. literalinclude:: ../includes/sqlite3/converter_point.py
787
788
789Default adapters and converters
790^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
791
792There are default adapters for the date and datetime types in the datetime
793module. They will be sent as ISO dates/ISO timestamps to SQLite.
794
795The default converters are registered under the name "date" for
796:class:`datetime.date` and under the name "timestamp" for
797:class:`datetime.datetime`.
798
799This way, you can use date/timestamps from Python without any additional
800fiddling in most cases. The format of the adapters is also compatible with the
801experimental SQLite date/time functions.
802
803The following example demonstrates this.
804
805.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
806
807
808.. _sqlite3-controlling-transactions:
809
810Controlling Transactions
811------------------------
812
813By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandl48310cd2009-01-03 21:18:54 +0000814Data Modification Language (DML) statement (i.e.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000815``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
816implicitly before a non-DML, non-query statement (i. e.
817anything other than ``SELECT`` or the aforementioned).
Georg Brandl116aa622007-08-15 14:28:22 +0000818
819So if you are within a transaction and issue a command like ``CREATE TABLE
820...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
821before executing that command. There are two reasons for doing that. The first
822is that some of these commands don't work within transactions. The other reason
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000823is that sqlite3 needs to keep track of the transaction state (if a transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000824is active or not). The current transaction state is exposed through the
825:attr:`Connection.in_transaction` attribute of the connection object.
Georg Brandl116aa622007-08-15 14:28:22 +0000826
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000827You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl116aa622007-08-15 14:28:22 +0000828(or none at all) via the *isolation_level* parameter to the :func:`connect`
829call, or via the :attr:`isolation_level` property of connections.
830
831If you want **autocommit mode**, then set :attr:`isolation_level` to None.
832
833Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandla971c652008-11-07 09:39:56 +0000834statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
835"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl116aa622007-08-15 14:28:22 +0000836
Georg Brandl116aa622007-08-15 14:28:22 +0000837
838
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000839Using :mod:`sqlite3` efficiently
840--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842
843Using shortcut methods
844^^^^^^^^^^^^^^^^^^^^^^
845
846Using the nonstandard :meth:`execute`, :meth:`executemany` and
847:meth:`executescript` methods of the :class:`Connection` object, your code can
848be written more concisely because you don't have to create the (often
849superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
850objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000851objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +0000852directly using only a single call on the :class:`Connection` object.
853
854.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
855
856
857Accessing columns by name instead of by index
858^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
859
Georg Brandl22b34312009-07-26 14:54:51 +0000860One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000861:class:`sqlite3.Row` class designed to be used as a row factory.
862
863Rows wrapped with this class can be accessed both by index (like tuples) and
864case-insensitively by name:
865
866.. literalinclude:: ../includes/sqlite3/rowclass.py
867
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000868
869Using the connection as a context manager
870^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
871
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000872Connection objects can be used as context managers
873that automatically commit or rollback transactions. In the event of an
874exception, the transaction is rolled back; otherwise, the transaction is
875committed:
876
877.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +0000878
879
880Common issues
881-------------
882
883Multithreading
884^^^^^^^^^^^^^^
885
886Older SQLite versions had issues with sharing connections between threads.
887That's why the Python module disallows sharing connections and cursors between
888threads. If you still try to do so, you will get an exception at runtime.
889
890The only exception is calling the :meth:`~Connection.interrupt` method, which
891only makes sense to call from a different thread.
892
Gerhard Häringe0941c52010-10-03 21:47:06 +0000893.. rubric:: Footnotes
894
895.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumaran946eb862011-07-03 10:17:22 -0700896 default, because some platforms (notably Mac OS X) have SQLite
897 libraries which are compiled without this feature. To get loadable
898 extension support, you must pass --enable-loadable-sqlite-extensions to
899 configure.