| Registers a callable to convert the custom Python type *type* into one of |
| SQLite's supported types. The callable *callable* accepts as single parameter |
| the Python value, and must return a value of the following types: int, long, |
| float, str (UTF-8 encoded), unicode or buffer. |
| |
| |
| .. function:: complete_statement(sql) |
| |
n | Returns :const:`True` if the string *sql* one or more complete SQL statements |
n | Returns :const:`True` if the string *sql* contains one or more complete SQL |
| terminated by semicolons. It does not verify if the SQL is syntactically |
| statements terminated by semicolons. It does not verify that the SQL is |
| correct, only if there are no unclosed string literals and if the statement is |
| syntactically correct, only that there are no unclosed string literals and the |
| terminated by a semicolon. |
| statement is terminated by a semicolon. |
| |
n | This can be used to build a shell for SQLite, like in the following example: |
n | This can be used to build a shell for SQLite, as in the following example: |
| |
| |
n | .. include:: ../includes/sqlite3/complete_statement.py |
n | .. literalinclude:: ../includes/sqlite3/complete_statement.py |
| :literal: |
| |
| |
| .. function:: enable_callback_tracebacks(flag) |
| |
| By default you will not get any tracebacks in user-defined functions, |
| aggregates, converters, authorizer callbacks etc. If you want to debug them, you |
| can call this function with *flag* as True. Afterwards, you will get tracebacks |
| from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature |
| again. |
| |
| |
| .. _sqlite3-connection-objects: |
| |
| Connection Objects |
| ------------------ |
| |
n | .. class:: Connection |
| |
| A :class:`Connection` instance has the following attributes and methods: |
| A SQLite database connection has the following attributes and methods: |
| |
n | .. _sqlite3-connection-isolationlevel: |
| |
| |
| .. attribute:: XXX Class.isolation_level |
| .. attribute:: Connection.isolation_level |
| |
n | Get or set the current isolation level. None for autocommit mode or one of |
n | Get or set the current isolation level. :const:`None` for autocommit mode or |
| "DEFERRED", "IMMEDIATE" or "EXLUSIVE". See "Controlling Transactions", section |
| one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section |
| :ref:`sqlite3-controlling-transactions`, for a more detailed explanation. |
| :ref:`sqlite3-controlling-transactions` for a more detailed explanation. |
| |
| |
n | .. method:: XXX Class.cursor([cursorClass]) |
n | .. method:: Connection.cursor([cursorClass]) |
| |
| The cursor method accepts a single optional parameter *cursorClass*. If |
| supplied, this must be a custom cursor class that extends |
| :class:`sqlite3.Cursor`. |
| |
| |
n | .. method:: Connection.commit() |
| |
| This method commits the current transaction. If you don't call this method, |
| anything you did since the last call to ``commit()`` is not visible from from |
| other database connections. If you wonder why you don't see the data you've |
| written to the database, please check you didn't forget to call this method. |
| |
| .. method:: Connection.rollback() |
| |
| This method rolls back any changes to the database since the last call to |
| :meth:`commit`. |
| |
| .. method:: Connection.close() |
| |
| This closes the database connection. Note that this does not automatically |
| call :meth:`commit`. If you just close your database connection without |
| calling :meth:`commit` first, your changes will be lost! |
| |
| .. method:: XXX Class.execute(sql, [parameters]) |
| .. method:: Connection.execute(sql, [parameters]) |
| |
| This is a nonstandard shortcut that creates an intermediate cursor object by |
| calling the cursor method, then calls the cursor's :meth:`execute` method with |
| the parameters given. |
| |
| |
n | .. method:: XXX Class.executemany(sql, [parameters]) |
n | .. method:: Connection.executemany(sql, [parameters]) |
| |
| This is a nonstandard shortcut that creates an intermediate cursor object by |
| calling the cursor method, then calls the cursor's :meth:`executemany` method |
| with the parameters given. |
| |
n | |
| .. method:: XXX Class.executescript(sql_script) |
| .. method:: Connection.executescript(sql_script) |
| |
| This is a nonstandard shortcut that creates an intermediate cursor object by |
| calling the cursor method, then calls the cursor's :meth:`executescript` method |
| with the parameters given. |
| |
| |
n | .. method:: XXX Class.create_function(name, num_params, func) |
n | .. method:: Connection.create_function(name, num_params, func) |
| |
| Creates a user-defined function that you can later use from within SQL |
| statements under the function name *name*. *num_params* is the number of |
| parameters the function accepts, and *func* is a Python callable that is called |
| as the SQL function. |
| |
| The function can return any of the types supported by SQLite: unicode, str, int, |
| long, float, buffer and None. |
| |
| Example: |
| |
n | |
| .. include:: ../includes/sqlite3/md5func.py |
| .. literalinclude:: ../includes/sqlite3/md5func.py |
| :literal: |
| |
| |
n | .. method:: XXX Class.create_aggregate(name, num_params, aggregate_class) |
n | .. method:: Connection.create_aggregate(name, num_params, aggregate_class) |
| |
| Creates a user-defined aggregate function. |
| |
| The aggregate class must implement a ``step`` method, which accepts the number |
| of parameters *num_params*, and a ``finalize`` method which will return the |
| final result of the aggregate. |
| |
| The ``finalize`` method can return any of the types supported by SQLite: |
| unicode, str, int, long, float, buffer and None. |
| |
| Example: |
| |
n | |
| .. include:: ../includes/sqlite3/mysumaggr.py |
| .. literalinclude:: ../includes/sqlite3/mysumaggr.py |
| :literal: |
| |
| |
n | .. method:: XXX Class.create_collation(name, callable) |
n | .. method:: Connection.create_collation(name, callable) |
| |
| Creates a collation with the specified *name* and *callable*. The callable will |
| be passed two string arguments. It should return -1 if the first is ordered |
| lower than the second, 0 if they are ordered equal and 1 if the first is ordered |
| higher than the second. Note that this controls sorting (ORDER BY in SQL) so |
| your comparisons don't affect other SQL operations. |
| |
| Note that the callable will get its parameters as Python bytestrings, which will |
| normally be encoded in UTF-8. |
| |
| The following example shows a custom collation that sorts "the wrong way": |
| |
n | |
| .. include:: ../includes/sqlite3/collation_reverse.py |
| .. literalinclude:: ../includes/sqlite3/collation_reverse.py |
| :literal: |
| |
| To remove a collation, call ``create_collation`` with None as callable:: |
| |
| con.create_collation("reverse", None) |
| |
| |
n | .. method:: XXX Class.interrupt() |
n | .. method:: Connection.interrupt() |
| |
| You can call this method from a different thread to abort any queries that might |
| be executing on the connection. The query will then abort and the caller will |
| get an exception. |
| |
| |
n | .. method:: XXX Class.set_authorizer(authorizer_callback) |
n | .. method:: Connection.set_authorizer(authorizer_callback) |
| |
| This routine registers a callback. The callback is invoked for each attempt to |
| access a column of a table in the database. The callback should return |
| :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL |
| statement should be aborted with an error and :const:`SQLITE_IGNORE` if the |
| column should be treated as a NULL value. These constants are available in the |
| :mod:`sqlite3` module. |
| |
| The first argument to the callback signifies what kind of operation is to be |
| authorized. The second and third argument will be arguments or :const:`None` |
| depending on the first argument. The 4th argument is the name of the database |
n | ("main", "temp", etc.) if applicable. The 5th argument is the name of the inner- |
n | ("main", "temp", etc.) if applicable. The 5th argument is the name of the |
| most trigger or view that is responsible for the access attempt or :const:`None` |
| inner-most trigger or view that is responsible for the access attempt or |
| if this access attempt is directly from input SQL code. |
| :const:`None` if this access attempt is directly from input SQL code. |
| |
| Please consult the SQLite documentation about the possible values for the first |
| argument and the meaning of the second and third argument depending on the first |
| one. All necessary constants are available in the :mod:`sqlite3` module. |
| |
| |
n | .. method:: Connection.set_progress_handler(handler, n) |
| |
| .. versionadded:: 2.6 |
| |
| This routine registers a callback. The callback is invoked for every *n* |
| instructions of the SQLite virtual machine. This is useful if you want to |
| get called from SQLite during long-running operations, for example to update |
| a GUI. |
| |
| If you want to clear any previously installed progress handler, call the |
| method with :const:`None` for *handler*. |
| |
| |
| .. attribute:: XXX Class.row_factory |
| .. attribute:: Connection.row_factory |
| |
| You can change this attribute to a callable that accepts the cursor and the |
| original row as a tuple and will return the real result row. This way, you can |
| implement more advanced ways of returning results, such as returning an object |
| that can also access columns by name. |
| |
| Example: |
| |
n | |
| .. include:: ../includes/sqlite3/row_factory.py |
| .. literalinclude:: ../includes/sqlite3/row_factory.py |
| :literal: |
| |
n | If returning a tuple doesn't suffice and you want name-based access to columns, |
n | If returning a tuple doesn't suffice and you want name-based access to |
| you should consider setting :attr:`row_factory` to the highly-optimized |
| columns, you should consider setting :attr:`row_factory` to the |
| :class:`sqlite3.Row` type. :class:`Row` provides both index-based and case- |
| highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both |
| insensitive name-based access to columns with almost no memory overhead. It will |
| index-based and case-insensitive name-based access to columns with almost no |
| probably be better than your own custom dictionary-based approach or even a |
| memory overhead. It will probably be better than your own custom |
| db_row based solution. |
| dictionary-based approach or even a db_row based solution. |
| |
n | .. % XXX what's a db_row-based solution? |
n | .. XXX what's a db_row-based solution? |
| |
| |
n | .. attribute:: XXX Class.text_factory |
n | .. attribute:: Connection.text_factory |
| |
n | Using this attribute you can control what objects are returned for the TEXT data |
n | Using this attribute you can control what objects are returned for the ``TEXT`` |
| type. By default, this attribute is set to :class:`unicode` and the |
| data type. By default, this attribute is set to :class:`unicode` and the |
| :mod:`sqlite3` module will return Unicode objects for TEXT. If you want to |
| :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to |
| return bytestrings instead, you can set it to :class:`str`. |
| |
| For efficiency reasons, there's also a way to return Unicode objects only for |
| non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to |
| :const:`sqlite3.OptimizedUnicode`. |
| |
| You can also set it to any other callable that accepts a single bytestring |
| parameter and returns the resulting object. |
| |
| See the following example code for illustration: |
| |
n | |
| .. include:: ../includes/sqlite3/text_factory.py |
| .. literalinclude:: ../includes/sqlite3/text_factory.py |
| :literal: |
| |
| |
n | .. attribute:: XXX Class.total_changes |
n | .. attribute:: Connection.total_changes |
| |
| Returns the total number of database rows that have been modified, inserted, or |
| deleted since the database connection was opened. |
| |
| |
n | .. attribute:: Connection.iterdump |
| |
| Returns an iterator to dump the database in an SQL text format. Useful when |
| saving an in-memory database for later restoration. This function provides |
| the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3` |
| shell. |
| |
| .. versionadded:: 2.6 |
| |
| Example:: |
| |
| # Convert file existing_db.db to SQL dump file dump.sql |
| import sqlite3, os |
| |
| con = sqlite3.connect('existing_db.db') |
| with open('dump.sql', 'w') as f: |
| for line in con.iterdump(): |
| f.write('%s\n' % line) |
| |
| |
| .. _sqlite3-cursor-objects: |
| |
| Cursor Objects |
| -------------- |
| |
n | A :class:`Cursor` instance has the following attributes and methods: |
n | .. class:: Cursor |
| |
n | A SQLite database cursor has the following attributes and methods: |
| |
n | .. method:: XXX Class.execute(sql, [parameters]) |
n | .. method:: Cursor.execute(sql, [parameters]) |
| |
n | Executes a SQL statement. The SQL statement may be parametrized (i. e. |
n | Executes an SQL statement. The SQL statement may be parametrized (i. e. |
| placeholders instead of SQL literals). The :mod:`sqlite3` module supports two |
| kinds of placeholders: question marks (qmark style) and named placeholders |
| (named style). |
| |
| This example shows how to use parameters with qmark style: |
| |
n | |
| .. include:: ../includes/sqlite3/execute_1.py |
| .. literalinclude:: ../includes/sqlite3/execute_1.py |
| :literal: |
| |
| This example shows how to use the named style: |
| |
n | |
| .. include:: ../includes/sqlite3/execute_2.py |
| .. literalinclude:: ../includes/sqlite3/execute_2.py |
| :literal: |
| |
| :meth:`execute` will only execute a single SQL statement. If you try to execute |
| more than one statement with it, it will raise a Warning. Use |
| :meth:`executescript` if you want to execute multiple SQL statements with one |
| call. |
| |
| |
n | .. method:: XXX Class.executemany(sql, seq_of_parameters) |
n | .. method:: Cursor.executemany(sql, seq_of_parameters) |
| |
n | Executes a SQL command against all parameter sequences or mappings found in the |
n | Executes an SQL command against all parameter sequences or mappings found in |
| sequence *sql*. The :mod:`sqlite3` module also allows using an iterator yielding |
| the sequence *sql*. The :mod:`sqlite3` module also allows using an |
| parameters instead of a sequence. |
| :term:`iterator` yielding parameters instead of a sequence. |
| |
n | |
| .. include:: ../includes/sqlite3/executemany_1.py |
| .. literalinclude:: ../includes/sqlite3/executemany_1.py |
| :literal: |
| |
n | Here's a shorter example using a generator: |
n | Here's a shorter example using a :term:`generator`: |
| |
n | |
| .. include:: ../includes/sqlite3/executemany_2.py |
| .. literalinclude:: ../includes/sqlite3/executemany_2.py |
| :literal: |
| |
| |
n | .. method:: XXX Class.executescript(sql_script) |
n | .. method:: Cursor.executescript(sql_script) |
| |
| This is a nonstandard convenience method for executing multiple SQL statements |
n | at once. It issues a COMMIT statement first, then executes the SQL script it |
n | at once. It issues a ``COMMIT`` statement first, then executes the SQL script it |
| gets as a parameter. |
| |
| *sql_script* can be a bytestring or a Unicode string. |
| |
| Example: |
| |
n | |
| .. include:: ../includes/sqlite3/executescript.py |
| .. literalinclude:: ../includes/sqlite3/executescript.py |
| :literal: |
| |
| |
n | .. method:: Cursor.fetchone() |
| |
| Fetches the next row of a query result set, returning a single sequence, |
| or :const:`None` when no more data is available. |
| |
| |
| .. method:: Cursor.fetchmany([size=cursor.arraysize]) |
| |
| Fetches the next set of rows of a query result, returning a list. An empty |
| list is returned when no more rows are available. |
| |
| The number of rows to fetch per call is specified by the *size* parameter. |
| If it is not given, the cursor's arraysize determines the number of rows |
| to be fetched. The method should try to fetch as many rows as indicated by |
| the size parameter. If this is not possible due to the specified number of |
| rows not being available, fewer rows may be returned. |
| |
| Note there are performance considerations involved with the *size* parameter. |
| For optimal performance, it is usually best to use the arraysize attribute. |
| If the *size* parameter is used, then it is best for it to retain the same |
| value from one :meth:`fetchmany` call to the next. |
| |
| .. method:: Cursor.fetchall() |
| |
| Fetches all (remaining) rows of a query result, returning a list. Note that |
| the cursor's arraysize attribute can affect the performance of this operation. |
| An empty list is returned when no rows are available. |
| |
| |
| .. attribute:: XXX Class.rowcount |
| .. attribute:: Cursor.rowcount |
| |
| Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this |
| attribute, the database engine's own support for the determination of "rows |
| affected"/"rows selected" is quirky. |
| |
n | For ``SELECT`` statements, :attr:`rowcount` is always None because we cannot |
| determine the number of rows a query produced until all rows were fetched. |
| |
| For ``DELETE`` statements, SQLite reports :attr:`rowcount` as 0 if you make a |
| ``DELETE FROM table`` without any condition. |
| |
| For :meth:`executemany` statements, the number of modifications are summed up |
| into :attr:`rowcount`. |
| |
| As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in |
n | case no executeXX() has been performed on the cursor or the rowcount of the last |
n | case no ``executeXX()`` has been performed on the cursor or the rowcount of the |
| operation is not determinable by the interface". |
| last operation is not determinable by the interface". |
| |
| This includes ``SELECT`` statements because we cannot determine the number of |
| rows a query produced until all rows were fetched. |
| |
| .. attribute:: Cursor.lastrowid |
| |
| This read-only attribute provides the rowid of the last modified row. It is |
| only set if you issued a ``INSERT`` statement using the :meth:`execute` |
| method. For operations other than ``INSERT`` or when :meth:`executemany` is |
| called, :attr:`lastrowid` is set to :const:`None`. |
| |
| .. attribute:: Cursor.description |
| |
| This read-only attribute provides the column names of the last query. To |
| remain compatible with the Python DB API, it returns a 7-tuple for each |
| column where the last six items of each tuple are :const:`None`. |
| |
| It is set for ``SELECT`` statements without any matching rows as well. |
| |
| .. _sqlite3-row-objects: |
| |
| Row Objects |
| ----------- |
| |
| .. class:: Row |
| |
| A :class:`Row` instance serves as a highly optimized |
| :attr:`~Connection.row_factory` for :class:`Connection` objects. |
| It tries to mimic a tuple in most of its features. |
| |
| It supports mapping access by column name and index, iteration, |
| representation, equality testing and :func:`len`. |
| |
| If two :class:`Row` objects have exactly the same columns and their |
| members are equal, they compare equal. |
| |
| .. versionchanged:: 2.6 |
| Added iteration and equality (hashability). |
| |
| .. method:: keys |
| |
| This method returns a tuple of column names. Immediately after a query, |
| it is the first member of each tuple in :attr:`Cursor.description`. |
| |
| .. versionadded:: 2.6 |
| |
| Let's assume we initialize a table as in the example given above:: |
| |
| conn = sqlite3.connect(":memory:") |
| c = conn.cursor() |
| c.execute('''create table stocks |
| (date text, trans text, symbol text, |
| qty real, price real)''') |
| c.execute("""insert into stocks |
| values ('2006-01-05','BUY','RHAT',100,35.14)""") |
| conn.commit() |
| c.close() |
| |
| Now we plug :class:`Row` in:: |
| |
| >>> conn.row_factory = sqlite3.Row |
| >>> c = conn.cursor() |
| >>> c.execute('select * from stocks') |
| <sqlite3.Cursor object at 0x7f4e7dd8fa80> |
| >>> r = c.fetchone() |
| >>> type(r) |
| <type 'sqlite3.Row'> |
| >>> r |
| (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001) |
| >>> len(r) |
| 5 |
| >>> r[2] |
| u'RHAT' |
| >>> r.keys() |
| ['date', 'trans', 'symbol', 'qty', 'price'] |
| >>> r['qty'] |
| 100.0 |
| >>> for member in r: print member |
| ... |
| 2006-01-05 |
| BUY |
| RHAT |
| 100.0 |
| 35.14 |
| |
| |
| .. _sqlite3-types: |
| |
| SQLite and Python types |
| ----------------------- |
| |
| |
| Introduction |
| ^^^^^^^^^^^^ |
| |
n | SQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB. |
n | SQLite natively supports the following types: ``NULL``, ``INTEGER``, |
| ``REAL``, ``TEXT``, ``BLOB``. |
| |
| The following Python types can thus be sent to SQLite without any problem: |
| |
n | +------------------------+-------------+ |
n | +-----------------------------+-------------+ |
| | Python type | SQLite type | |
| | Python type | SQLite type | |
| +========================+=============+ |
| +=============================+=============+ |
| | ``None`` | NULL | |
| | :const:`None` | ``NULL`` | |
| +------------------------+-------------+ |
| +-----------------------------+-------------+ |
| | ``int`` | INTEGER | |
| | :class:`int` | ``INTEGER`` | |
| +------------------------+-------------+ |
| +-----------------------------+-------------+ |
| | ``long`` | INTEGER | |
| | :class:`long` | ``INTEGER`` | |
| +------------------------+-------------+ |
| +-----------------------------+-------------+ |
| | ``float`` | REAL | |
| | :class:`float` | ``REAL`` | |
| +------------------------+-------------+ |
| +-----------------------------+-------------+ |
| | ``str (UTF8-encoded)`` | TEXT | |
| | :class:`str` (UTF8-encoded) | ``TEXT`` | |
| +------------------------+-------------+ |
| +-----------------------------+-------------+ |
| | ``unicode`` | TEXT | |
| | :class:`unicode` | ``TEXT`` | |
| +------------------------+-------------+ |
| +-----------------------------+-------------+ |
| | ``buffer`` | BLOB | |
| | :class:`buffer` | ``BLOB`` | |
| +------------------------+-------------+ |
| +-----------------------------+-------------+ |
| |
| This is how SQLite types are converted to Python types by default: |
| |
n | +-------------+---------------------------------------------+ |
n | +-------------+----------------------------------------------+ |
| | SQLite type | Python type | |
| | SQLite type | Python type | |
| +=============+=============================================+ |
| +=============+==============================================+ |
| | ``NULL`` | None | |
| | ``NULL`` | :const:`None` | |
| +-------------+---------------------------------------------+ |
| +-------------+----------------------------------------------+ |
| | ``INTEGER`` | int or long, depending on size | |
| | ``INTEGER`` | :class:`int` or :class:`long`, | |
| | | depending on size | |
| +-------------+---------------------------------------------+ |
| +-------------+----------------------------------------------+ |
| | ``REAL`` | float | |
| | ``REAL`` | :class:`float` | |
| +-------------+---------------------------------------------+ |
| +-------------+----------------------------------------------+ |
| | ``TEXT`` | depends on text_factory, unicode by default | |
| | ``TEXT`` | depends on :attr:`~Connection.text_factory`, | |
| | | :class:`unicode` by default | |
| +-------------+---------------------------------------------+ |
| +-------------+----------------------------------------------+ |
| | ``BLOB`` | buffer | |
| | ``BLOB`` | :class:`buffer` | |
| +-------------+---------------------------------------------+ |
| +-------------+----------------------------------------------+ |
| |
| The type system of the :mod:`sqlite3` module is extensible in two ways: you can |
| store additional Python types in a SQLite database via object adaptation, and |
| you can let the :mod:`sqlite3` module convert SQLite types to different Python |
| types via converters. |
| |
| |
| Using adapters to store additional Python types in SQLite databases |