Added section on passing contextual information to logging and documentation for...
[python.git] / Doc / library / sqlite3.rst
blobc42a1d7aca753c3bb8b9dabd21e2eeaaf0887cf3
2 :mod:`sqlite3` --- DB-API 2.0 interface for SQLite databases
3 ============================================================
5 .. module:: sqlite3
6    :synopsis: A DB-API 2.0 implementation using SQLite 3.x.
7 .. sectionauthor:: Gerhard Häring <gh@ghaering.de>
10 .. versionadded:: 2.5
12 SQLite is a C library that provides a lightweight disk-based database that
13 doesn't require a separate server process and allows accessing the database
14 using a nonstandard variant of the SQL query language. Some applications can use
15 SQLite for internal data storage.  It's also possible to prototype an
16 application using SQLite and then port the code to a larger database such as
17 PostgreSQL or Oracle.
19 pysqlite was written by Gerhard Häring and provides a SQL interface compliant
20 with the DB-API 2.0 specification described by :pep:`249`.
22 To use the module, you must first create a :class:`Connection` object that
23 represents the database.  Here the data will be stored in the
24 :file:`/tmp/example` file::
26    conn = sqlite3.connect('/tmp/example')
28 You can also supply the special name ``:memory:`` to create a database in RAM.
30 Once you have a :class:`Connection`, you can create a :class:`Cursor`  object
31 and call its :meth:`execute` method to perform SQL commands::
33    c = conn.cursor()
35    # Create table
36    c.execute('''create table stocks
37    (date text, trans text, symbol text,
38     qty real, price real)''')
40    # Insert a row of data
41    c.execute("""insert into stocks
42              values ('2006-01-05','BUY','RHAT',100,35.14)""")
44    # Save (commit) the changes
45    conn.commit()
47    # We can also close the cursor if we are done with it
48    c.close()
50 Usually your SQL operations will need to use values from Python variables.  You
51 shouldn't assemble your query using Python's string operations because doing so
52 is insecure; it makes your program vulnerable to an SQL injection attack.
54 Instead, use the DB-API's parameter substitution.  Put ``?`` as a placeholder
55 wherever you want to use a value, and then provide a tuple of values as the
56 second argument to the cursor's :meth:`execute` method.  (Other database modules
57 may use a different placeholder, such as ``%s`` or ``:1``.) For example::
59    # Never do this -- insecure!
60    symbol = 'IBM'
61    c.execute("... where symbol = '%s'" % symbol)
63    # Do this instead
64    t = (symbol,)
65    c.execute('select * from stocks where symbol=?', t)
67    # Larger example
68    for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
69              ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
70              ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
71             ):
72        c.execute('insert into stocks values (?,?,?,?,?)', t)
74 To retrieve data after executing a SELECT statement, you can either treat the
75 cursor as an :term:`iterator`, call the cursor's :meth:`fetchone` method to
76 retrieve a single matching row, or call :meth:`fetchall` to get a list of the
77 matching rows.
79 This example uses the iterator form::
81    >>> c = conn.cursor()
82    >>> c.execute('select * from stocks order by price')
83    >>> for row in c:
84    ...    print row
85    ...
86    (u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
87    (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
88    (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
89    (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
90    >>>
93 .. seealso::
95    http://www.pysqlite.org
96       The pysqlite web page.
98    http://www.sqlite.org
99       The SQLite web page; the documentation describes the syntax and the available
100       data types for the supported SQL dialect.
102    :pep:`249` - Database API Specification 2.0
103       PEP written by Marc-André Lemburg.
106 .. _sqlite3-module-contents:
108 Module functions and constants
109 ------------------------------
112 .. data:: PARSE_DECLTYPES
114    This constant is meant to be used with the *detect_types* parameter of the
115    :func:`connect` function.
117    Setting it makes the :mod:`sqlite3` module parse the declared type for each
118    column it returns.  It will parse out the first word of the declared type, i. e.
119    for "integer primary key", it will parse out "integer". Then for that column, it
120    will look into the converters dictionary and use the converter function
121    registered for that type there.  Converter names are case-sensitive!
124 .. data:: PARSE_COLNAMES
126    This constant is meant to be used with the *detect_types* parameter of the
127    :func:`connect` function.
129    Setting this makes the SQLite interface parse the column name for each column it
130    returns.  It will look for a string formed [mytype] in there, and then decide
131    that 'mytype' is the type of the column. It will try to find an entry of
132    'mytype' in the converters dictionary and then use the converter function found
133    there to return the value. The column name found in :attr:`cursor.description`
134    is only the first word of the column name, i.  e. if you use something like
135    ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
136    first blank for the column name: the column name would simply be "x".
139 .. function:: connect(database[, timeout, isolation_level, detect_types, factory])
141    Opens a connection to the SQLite database file *database*. You can use
142    ``":memory:"`` to open a database connection to a database that resides in RAM
143    instead of on disk.
145    When a database is accessed by multiple connections, and one of the processes
146    modifies the database, the SQLite database is locked until that transaction is
147    committed. The *timeout* parameter specifies how long the connection should wait
148    for the lock to go away until raising an exception. The default for the timeout
149    parameter is 5.0 (five seconds).
151    For the *isolation_level* parameter, please see the
152    :attr:`Connection.isolation_level` property of :class:`Connection` objects.
154    SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
155    you want to use other types you must add support for them yourself. The
156    *detect_types* parameter and the using custom **converters** registered with the
157    module-level :func:`register_converter` function allow you to easily do that.
159    *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
160    any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
161    type detection on.
163    By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
164    connect call.  You can, however, subclass the :class:`Connection` class and make
165    :func:`connect` use your class instead by providing your class for the *factory*
166    parameter.
168    Consult the section :ref:`sqlite3-types` of this manual for details.
170    The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
171    overhead. If you want to explicitly set the number of statements that are cached
172    for the connection, you can set the *cached_statements* parameter. The currently
173    implemented default is to cache 100 statements.
176 .. function:: register_converter(typename, callable)
178    Registers a callable to convert a bytestring from the database into a custom
179    Python type. The callable will be invoked for all database values that are of
180    the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
181    function for how the type detection works. Note that the case of *typename* and
182    the name of the type in your query must match!
185 .. function:: register_adapter(type, callable)
187    Registers a callable to convert the custom Python type *type* into one of
188    SQLite's supported types. The callable *callable* accepts as single parameter
189    the Python value, and must return a value of the following types: int, long,
190    float, str (UTF-8 encoded), unicode or buffer.
193 .. function:: complete_statement(sql)
195    Returns :const:`True` if the string *sql* contains one or more complete SQL
196    statements terminated by semicolons. It does not verify that the SQL is
197    syntactically correct, only that there are no unclosed string literals and the
198    statement is terminated by a semicolon.
200    This can be used to build a shell for SQLite, as in the following example:
203    .. literalinclude:: ../includes/sqlite3/complete_statement.py
206 .. function:: enable_callback_tracebacks(flag)
208    By default you will not get any tracebacks in user-defined functions,
209    aggregates, converters, authorizer callbacks etc. If you want to debug them, you
210    can call this function with *flag* as True. Afterwards, you will get tracebacks
211    from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
212    again.
215 .. _sqlite3-connection-objects:
217 Connection Objects
218 ------------------
220 A :class:`Connection` instance has the following attributes and methods:
222 .. attribute:: Connection.isolation_level
224    Get or set the current isolation level. None for autocommit mode or one of
225    "DEFERRED", "IMMEDIATE" or "EXLUSIVE". See section
226    :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
229 .. method:: Connection.cursor([cursorClass])
231    The cursor method accepts a single optional parameter *cursorClass*. If
232    supplied, this must be a custom cursor class that extends
233    :class:`sqlite3.Cursor`.
236 .. method:: Connection.execute(sql, [parameters])
238    This is a nonstandard shortcut that creates an intermediate cursor object by
239    calling the cursor method, then calls the cursor's :meth:`execute` method with
240    the parameters given.
243 .. method:: Connection.executemany(sql, [parameters])
245    This is a nonstandard shortcut that creates an intermediate cursor object by
246    calling the cursor method, then calls the cursor's :meth:`executemany` method
247    with the parameters given.
250 .. method:: Connection.executescript(sql_script)
252    This is a nonstandard shortcut that creates an intermediate cursor object by
253    calling the cursor method, then calls the cursor's :meth:`executescript` method
254    with the parameters given.
257 .. method:: Connection.create_function(name, num_params, func)
259    Creates a user-defined function that you can later use from within SQL
260    statements under the function name *name*. *num_params* is the number of
261    parameters the function accepts, and *func* is a Python callable that is called
262    as the SQL function.
264    The function can return any of the types supported by SQLite: unicode, str, int,
265    long, float, buffer and None.
267    Example:
269    .. literalinclude:: ../includes/sqlite3/md5func.py
272 .. method:: Connection.create_aggregate(name, num_params, aggregate_class)
274    Creates a user-defined aggregate function.
276    The aggregate class must implement a ``step`` method, which accepts the number
277    of parameters *num_params*, and a ``finalize`` method which will return the
278    final result of the aggregate.
280    The ``finalize`` method can return any of the types supported by SQLite:
281    unicode, str, int, long, float, buffer and None.
283    Example:
285    .. literalinclude:: ../includes/sqlite3/mysumaggr.py
288 .. method:: Connection.create_collation(name, callable)
290    Creates a collation with the specified *name* and *callable*. The callable will
291    be passed two string arguments. It should return -1 if the first is ordered
292    lower than the second, 0 if they are ordered equal and 1 if the first is ordered
293    higher than the second.  Note that this controls sorting (ORDER BY in SQL) so
294    your comparisons don't affect other SQL operations.
296    Note that the callable will get its parameters as Python bytestrings, which will
297    normally be encoded in UTF-8.
299    The following example shows a custom collation that sorts "the wrong way":
301    .. literalinclude:: ../includes/sqlite3/collation_reverse.py
303    To remove a collation, call ``create_collation`` with None as callable::
305       con.create_collation("reverse", None)
308 .. method:: Connection.interrupt()
310    You can call this method from a different thread to abort any queries that might
311    be executing on the connection. The query will then abort and the caller will
312    get an exception.
315 .. method:: Connection.set_authorizer(authorizer_callback)
317    This routine registers a callback. The callback is invoked for each attempt to
318    access a column of a table in the database. The callback should return
319    :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
320    statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
321    column should be treated as a NULL value. These constants are available in the
322    :mod:`sqlite3` module.
324    The first argument to the callback signifies what kind of operation is to be
325    authorized. The second and third argument will be arguments or :const:`None`
326    depending on the first argument. The 4th argument is the name of the database
327    ("main", "temp", etc.) if applicable. The 5th argument is the name of the
328    inner-most trigger or view that is responsible for the access attempt or
329    :const:`None` if this access attempt is directly from input SQL code.
331    Please consult the SQLite documentation about the possible values for the first
332    argument and the meaning of the second and third argument depending on the first
333    one. All necessary constants are available in the :mod:`sqlite3` module.
336 .. attribute:: Connection.row_factory
338    You can change this attribute to a callable that accepts the cursor and the
339    original row as a tuple and will return the real result row.  This way, you can
340    implement more advanced ways of returning results, such  as returning an object
341    that can also access columns by name.
343    Example:
345    .. literalinclude:: ../includes/sqlite3/row_factory.py
347    If returning a tuple doesn't suffice and you want name-based access to
348    columns, you should consider setting :attr:`row_factory` to the
349    highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
350    index-based and case-insensitive name-based access to columns with almost no
351    memory overhead. It will probably be better than your own custom
352    dictionary-based approach or even a db_row based solution.
354    .. XXX what's a db_row-based solution?
357 .. attribute:: Connection.text_factory
359    Using this attribute you can control what objects are returned for the TEXT data
360    type. By default, this attribute is set to :class:`unicode` and the
361    :mod:`sqlite3` module will return Unicode objects for TEXT. If you want to
362    return bytestrings instead, you can set it to :class:`str`.
364    For efficiency reasons, there's also a way to return Unicode objects only for
365    non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to
366    :const:`sqlite3.OptimizedUnicode`.
368    You can also set it to any other callable that accepts a single bytestring
369    parameter and returns the resulting object.
371    See the following example code for illustration:
373    .. literalinclude:: ../includes/sqlite3/text_factory.py
376 .. attribute:: Connection.total_changes
378    Returns the total number of database rows that have been modified, inserted, or
379    deleted since the database connection was opened.
382 .. _sqlite3-cursor-objects:
384 Cursor Objects
385 --------------
387 A :class:`Cursor` instance has the following attributes and methods:
390 .. method:: Cursor.execute(sql, [parameters])
392    Executes a SQL statement. The SQL statement may be parametrized (i. e.
393    placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
394    kinds of placeholders: question marks (qmark style) and named placeholders
395    (named style).
397    This example shows how to use parameters with qmark style:
399    .. literalinclude:: ../includes/sqlite3/execute_1.py
401    This example shows how to use the named style:
403    .. literalinclude:: ../includes/sqlite3/execute_2.py
405    :meth:`execute` will only execute a single SQL statement. If you try to execute
406    more than one statement with it, it will raise a Warning. Use
407    :meth:`executescript` if you want to execute multiple SQL statements with one
408    call.
411 .. method:: Cursor.executemany(sql, seq_of_parameters)
413    Executes a SQL command against all parameter sequences or mappings found in
414    the sequence *sql*.  The :mod:`sqlite3` module also allows using an
415    :term:`iterator` yielding parameters instead of a sequence.
417    .. literalinclude:: ../includes/sqlite3/executemany_1.py
419    Here's a shorter example using a :term:`generator`:
421    .. literalinclude:: ../includes/sqlite3/executemany_2.py
424 .. method:: Cursor.executescript(sql_script)
426    This is a nonstandard convenience method for executing multiple SQL statements
427    at once. It issues a COMMIT statement first, then executes the SQL script it
428    gets as a parameter.
430    *sql_script* can be a bytestring or a Unicode string.
432    Example:
434    .. literalinclude:: ../includes/sqlite3/executescript.py
437 .. attribute:: Cursor.rowcount
439    Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
440    attribute, the database engine's own support for the determination of "rows
441    affected"/"rows selected" is quirky.
443    For ``DELETE`` statements, SQLite reports :attr:`rowcount` as 0 if you make a
444    ``DELETE FROM table`` without any condition.
446    For :meth:`executemany` statements, the number of modifications are summed up
447    into :attr:`rowcount`.
449    As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
450    case no executeXX() has been performed on the cursor or the rowcount of the last
451    operation is not determinable by the interface".
453    This includes ``SELECT`` statements because we cannot determine the number of
454    rows a query produced until all rows were fetched.
457 .. _sqlite3-types:
459 SQLite and Python types
460 -----------------------
463 Introduction
464 ^^^^^^^^^^^^
466 SQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB.
468 The following Python types can thus be sent to SQLite without any problem:
470 +------------------------+-------------+
471 | Python type            | SQLite type |
472 +========================+=============+
473 | ``None``               | NULL        |
474 +------------------------+-------------+
475 | ``int``                | INTEGER     |
476 +------------------------+-------------+
477 | ``long``               | INTEGER     |
478 +------------------------+-------------+
479 | ``float``              | REAL        |
480 +------------------------+-------------+
481 | ``str (UTF8-encoded)`` | TEXT        |
482 +------------------------+-------------+
483 | ``unicode``            | TEXT        |
484 +------------------------+-------------+
485 | ``buffer``             | BLOB        |
486 +------------------------+-------------+
488 This is how SQLite types are converted to Python types by default:
490 +-------------+---------------------------------------------+
491 | SQLite type | Python type                                 |
492 +=============+=============================================+
493 | ``NULL``    | None                                        |
494 +-------------+---------------------------------------------+
495 | ``INTEGER`` | int or long, depending on size              |
496 +-------------+---------------------------------------------+
497 | ``REAL``    | float                                       |
498 +-------------+---------------------------------------------+
499 | ``TEXT``    | depends on text_factory, unicode by default |
500 +-------------+---------------------------------------------+
501 | ``BLOB``    | buffer                                      |
502 +-------------+---------------------------------------------+
504 The type system of the :mod:`sqlite3` module is extensible in two ways: you can
505 store additional Python types in a SQLite database via object adaptation, and
506 you can let the :mod:`sqlite3` module convert SQLite types to different Python
507 types via converters.
510 Using adapters to store additional Python types in SQLite databases
511 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
513 As described before, SQLite supports only a limited set of types natively. To
514 use other Python types with SQLite, you must **adapt** them to one of the
515 sqlite3 module's supported types for SQLite: one of NoneType, int, long, float,
516 str, unicode, buffer.
518 The :mod:`sqlite3` module uses Python object adaptation, as described in
519 :pep:`246` for this.  The protocol to use is :class:`PrepareProtocol`.
521 There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
522 type to one of the supported ones.
525 Letting your object adapt itself
526 """"""""""""""""""""""""""""""""
528 This is a good approach if you write the class yourself. Let's suppose you have
529 a class like this::
531    class Point(object):
532        def __init__(self, x, y):
533            self.x, self.y = x, y
535 Now you want to store the point in a single SQLite column.  First you'll have to
536 choose one of the supported types first to be used for representing the point.
537 Let's just use str and separate the coordinates using a semicolon. Then you need
538 to give your class a method ``__conform__(self, protocol)`` which must return
539 the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
541 .. literalinclude:: ../includes/sqlite3/adapter_point_1.py
544 Registering an adapter callable
545 """""""""""""""""""""""""""""""
547 The other possibility is to create a function that converts the type to the
548 string representation and register the function with :meth:`register_adapter`.
550 .. note::
552    The type/class to adapt must be a :term:`new-style class`, i. e. it must have
553    :class:`object` as one of its bases.
555 .. literalinclude:: ../includes/sqlite3/adapter_point_2.py
557 The :mod:`sqlite3` module has two default adapters for Python's built-in
558 :class:`datetime.date` and :class:`datetime.datetime` types.  Now let's suppose
559 we want to store :class:`datetime.datetime` objects not in ISO representation,
560 but as a Unix timestamp.
562 .. literalinclude:: ../includes/sqlite3/adapter_datetime.py
565 Converting SQLite values to custom Python types
566 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
568 Writing an adapter lets you send custom Python types to SQLite. But to make it
569 really useful we need to make the Python to SQLite to Python roundtrip work.
571 Enter converters.
573 Let's go back to the :class:`Point` class. We stored the x and y coordinates
574 separated via semicolons as strings in SQLite.
576 First, we'll define a converter function that accepts the string as a parameter
577 and constructs a :class:`Point` object from it.
579 .. note::
581    Converter functions **always** get called with a string, no matter under which
582    data type you sent the value to SQLite.
584 .. note::
586    Converter names are looked up in a case-sensitive manner.
590    def convert_point(s):
591        x, y = map(float, s.split(";"))
592        return Point(x, y)
594 Now you need to make the :mod:`sqlite3` module know that what you select from
595 the database is actually a point. There are two ways of doing this:
597 * Implicitly via the declared type
599 * Explicitly via the column name
601 Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
602 for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
604 The following example illustrates both approaches.
606 .. literalinclude:: ../includes/sqlite3/converter_point.py
609 Default adapters and converters
610 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
612 There are default adapters for the date and datetime types in the datetime
613 module. They will be sent as ISO dates/ISO timestamps to SQLite.
615 The default converters are registered under the name "date" for
616 :class:`datetime.date` and under the name "timestamp" for
617 :class:`datetime.datetime`.
619 This way, you can use date/timestamps from Python without any additional
620 fiddling in most cases. The format of the adapters is also compatible with the
621 experimental SQLite date/time functions.
623 The following example demonstrates this.
625 .. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
628 .. _sqlite3-controlling-transactions:
630 Controlling Transactions
631 ------------------------
633 By default, the :mod:`sqlite3` module opens transactions implicitly before a
634 Data Modification Language (DML)  statement (i.e. INSERT/UPDATE/DELETE/REPLACE),
635 and commits transactions implicitly before a non-DML, non-query statement (i. e.
636 anything other than SELECT/INSERT/UPDATE/DELETE/REPLACE).
638 So if you are within a transaction and issue a command like ``CREATE TABLE
639 ...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
640 before executing that command. There are two reasons for doing that. The first
641 is that some of these commands don't work within transactions. The other reason
642 is that pysqlite needs to keep track of the transaction state (if a transaction
643 is active or not).
645 You can control which kind of "BEGIN" statements pysqlite implicitly executes
646 (or none at all) via the *isolation_level* parameter to the :func:`connect`
647 call, or via the :attr:`isolation_level` property of connections.
649 If you want **autocommit mode**, then set :attr:`isolation_level` to None.
651 Otherwise leave it at its default, which will result in a plain "BEGIN"
652 statement, or set it to one of SQLite's supported isolation levels: DEFERRED,
653 IMMEDIATE or EXCLUSIVE.
655 As the :mod:`sqlite3` module needs to keep track of the transaction state, you
656 should not use ``OR ROLLBACK`` or ``ON CONFLICT ROLLBACK`` in your SQL. Instead,
657 catch the :exc:`IntegrityError` and call the :meth:`rollback` method of the
658 connection yourself.
661 Using pysqlite efficiently
662 --------------------------
665 Using shortcut methods
666 ^^^^^^^^^^^^^^^^^^^^^^
668 Using the nonstandard :meth:`execute`, :meth:`executemany` and
669 :meth:`executescript` methods of the :class:`Connection` object, your code can
670 be written more concisely because you don't have to create the (often
671 superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
672 objects are created implicitly and these shortcut methods return the cursor
673 objects. This way, you can execute a SELECT statement and iterate over it
674 directly using only a single call on the :class:`Connection` object.
676 .. literalinclude:: ../includes/sqlite3/shortcut_methods.py
679 Accessing columns by name instead of by index
680 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
682 One useful feature of the :mod:`sqlite3` module is the builtin
683 :class:`sqlite3.Row` class designed to be used as a row factory.
685 Rows wrapped with this class can be accessed both by index (like tuples) and
686 case-insensitively by name:
688 .. literalinclude:: ../includes/sqlite3/rowclass.py