rest25/library/sqlite3.rst => rest262/library/sqlite3.rst
n1- 
2:mod:`sqlite3` --- DB-API 2.0 interface for SQLite databases
3============================================================
4
5.. module:: sqlite3
6   :synopsis: A DB-API 2.0 implementation using SQLite 3.x.
7.. sectionauthor:: Gerhard Häring <gh@ghaering.de>
8
9
23represents the database.  Here the data will be stored in the
24:file:`/tmp/example` file::
25
26   conn = sqlite3.connect('/tmp/example')
27
28You can also supply the special name ``:memory:`` to create a database in RAM.
29
30Once you have a :class:`Connection`, you can create a :class:`Cursor`  object
n31-and call its :meth:`execute` method to perform SQL commands::
n30+and call its :meth:`~Cursor.execute` method to perform SQL commands::
32
33   c = conn.cursor()
34
35   # Create table
36   c.execute('''create table stocks
37   (date text, trans text, symbol text,
38    qty real, price real)''')
39
40   # Insert a row of data
41   c.execute("""insert into stocks
42             values ('2006-01-05','BUY','RHAT',100,35.14)""")
43
n43+   # Save (commit) the changes
44+   conn.commit()
45+ 
46+   # We can also close the cursor if we are done with it
47+   c.close()
48+ 
44Usually your SQL operations will need to use values from Python variables.  You
45shouldn't assemble your query using Python's string operations because doing so
46is insecure; it makes your program vulnerable to an SQL injection attack.
47
48Instead, use the DB-API's parameter substitution.  Put ``?`` as a placeholder
49wherever you want to use a value, and then provide a tuple of values as the
n50-second argument to the cursor's :meth:`execute` method.  (Other database modules
n55+second argument to the cursor's :meth:`~Cursor.execute` method.  (Other database modules
51may use a different placeholder, such as ``%s`` or ``:1``.) For example::
52
53   # Never do this -- insecure!
54   symbol = 'IBM'
55   c.execute("... where symbol = '%s'" % symbol)
56
57   # Do this instead
58   t = (symbol,)
59   c.execute('select * from stocks where symbol=?', t)
60
61   # Larger example
n62-   for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
n67+   for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
63             ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
64             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
n65-            ):
n70+            ]:
66       c.execute('insert into stocks values (?,?,?,?,?)', t)
67
n68-To retrieve data after executing a SELECT statement, you can either  treat the
n73+To retrieve data after executing a SELECT statement, you can either treat the
69-cursor as an iterator, call the cursor's :meth:`fetchone` method to retrieve a
74+cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
70-single matching row,  or call :meth:`fetchall` to get a list of the matching
75+retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
71-rows.
76+matching rows.
72
73This example uses the iterator form::
74
75   >>> c = conn.cursor()
76   >>> c.execute('select * from stocks order by price')
77   >>> for row in c:
78   ...    print row
79   ...
104
105
106.. data:: PARSE_DECLTYPES
107
108   This constant is meant to be used with the *detect_types* parameter of the
109   :func:`connect` function.
110
111   Setting it makes the :mod:`sqlite3` module parse the declared type for each
n112-   column it returns.  It will parse out the first word of the declared type, i. e.
n117+   column it returns.  It will parse out the first word of the declared type,
113-   for "integer primary key", it will parse out "integer". Then for that column, it
118+   i. e.  for "integer primary key", it will parse out "integer", or for
119+   "number(10)" it will parse out "number". Then for that column, it will look
114-   will look into the converters dictionary and use the converter function
120+   into the converters dictionary and use the converter function registered for
115-   registered for that type there.  Converter names are case-sensitive!
121+   that type there.
116
117
118.. data:: PARSE_COLNAMES
119
120   This constant is meant to be used with the *detect_types* parameter of the
121   :func:`connect` function.
122
123   Setting this makes the SQLite interface parse the column name for each column it
124   returns.  It will look for a string formed [mytype] in there, and then decide
125   that 'mytype' is the type of the column. It will try to find an entry of
126   'mytype' in the converters dictionary and then use the converter function found
n127-   there to return the value. The column name found in :attr:`cursor.description`
n133+   there to return the value. The column name found in :attr:`Cursor.description`
128   is only the first word of the column name, i.  e. if you use something like
129   ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
130   first blank for the column name: the column name would simply be "x".
131
132
133.. function:: connect(database[, timeout, isolation_level, detect_types, factory])
134
135   Opens a connection to the SQLite database file *database*. You can use
137   instead of on disk.
138
139   When a database is accessed by multiple connections, and one of the processes
140   modifies the database, the SQLite database is locked until that transaction is
141   committed. The *timeout* parameter specifies how long the connection should wait
142   for the lock to go away until raising an exception. The default for the timeout
143   parameter is 5.0 (five seconds).
144
n145-   For the *isolation_level* parameter, please see the :attr:`isolation_level`
n151+   For the *isolation_level* parameter, please see the
146-   property of :class:`Connection` objects in section
152+   :attr:`Connection.isolation_level` property of :class:`Connection` objects.
147-   :ref:`sqlite3-connection-isolationlevel`.
148
149   SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
n150-   you want to use other types, like you have to add support for them yourself. The
n155+   you want to use other types you must add support for them yourself. The
151   *detect_types* parameter and the using custom **converters** registered with the
152   module-level :func:`register_converter` function allow you to easily do that.
153
154   *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
155   any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
156   type detection on.
157
158   By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
182   Registers a callable to convert the custom Python type *type* into one of
183   SQLite's supported types. The callable *callable* accepts as single parameter
184   the Python value, and must return a value of the following types: int, long,
185   float, str (UTF-8 encoded), unicode or buffer.
186
187
188.. function:: complete_statement(sql)
189
n190-   Returns :const:`True` if the string *sql* one or more complete SQL statements
n195+   Returns :const:`True` if the string *sql* contains one or more complete SQL
191-   terminated by semicolons. It does not verify if the SQL is syntactically
196+   statements terminated by semicolons. It does not verify that the SQL is
192-   correct, only if there are no unclosed string literals and if the statement is
197+   syntactically correct, only that there are no unclosed string literals and the
193-   terminated by a semicolon.
198+   statement is terminated by a semicolon.
194
n195-   This can be used to build a shell for SQLite, like in the following example:
n200+   This can be used to build a shell for SQLite, as in the following example:
196
197
n198-   .. include:: ../includes/sqlite3/complete_statement.py
n203+   .. literalinclude:: ../includes/sqlite3/complete_statement.py
199-      :literal:
200
201
202.. function:: enable_callback_tracebacks(flag)
203
204   By default you will not get any tracebacks in user-defined functions,
205   aggregates, converters, authorizer callbacks etc. If you want to debug them, you
206   can call this function with *flag* as True. Afterwards, you will get tracebacks
207   from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
208   again.
209
210
211.. _sqlite3-connection-objects:
212
213Connection Objects
214------------------
215
n220+.. class:: Connection
221+ 
216-:class:`Connection` instance has the following attributes and methods:
222+   SQLite database connection has the following attributes and methods:
217
n218-.. _sqlite3-connection-isolationlevel:
219- 
220- 
221-.. attribute:: XXX Class.isolation_level
224+.. attribute:: Connection.isolation_level
222
n223-   Get or set the current isolation level. None for autocommit mode or one of
n226+   Get or set the current isolation level. :const:`None` for autocommit mode or
224-   "DEFERRED", "IMMEDIATE" or "EXLUSIVE". See "Controlling Transactions",  section
227+   one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
225-   :ref:`sqlite3-controlling-transactions`, for a more detailed explanation.
228+   :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
226
227
n228-.. method:: XXX Class.cursor([cursorClass])
n231+.. method:: Connection.cursor([cursorClass])
229
230   The cursor method accepts a single optional parameter *cursorClass*. If
231   supplied, this must be a custom cursor class that extends
232   :class:`sqlite3.Cursor`.
233
234
n238+.. method:: Connection.commit()
239+ 
240+   This method commits the current transaction. If you don't call this method,
241+   anything you did since the last call to ``commit()`` is not visible from from
242+   other database connections. If you wonder why you don't see the data you've
243+   written to the database, please check you didn't forget to call this method.
244+ 
245+.. method:: Connection.rollback()
246+ 
247+   This method rolls back any changes to the database since the last call to
248+   :meth:`commit`.
249+ 
250+.. method:: Connection.close()
251+ 
252+   This closes the database connection. Note that this does not automatically
253+   call :meth:`commit`. If you just close your database connection without
254+   calling :meth:`commit` first, your changes will be lost!
255+ 
235-.. method:: XXX Class.execute(sql, [parameters])
256+.. method:: Connection.execute(sql, [parameters])
236
237   This is a nonstandard shortcut that creates an intermediate cursor object by
238   calling the cursor method, then calls the cursor's :meth:`execute` method with
239   the parameters given.
240
241
n242-.. method:: XXX Class.executemany(sql, [parameters])
n263+.. method:: Connection.executemany(sql, [parameters])
243
244   This is a nonstandard shortcut that creates an intermediate cursor object by
245   calling the cursor method, then calls the cursor's :meth:`executemany` method
246   with the parameters given.
247
n248- 
249-.. method:: XXX Class.executescript(sql_script)
269+.. method:: Connection.executescript(sql_script)
250
251   This is a nonstandard shortcut that creates an intermediate cursor object by
252   calling the cursor method, then calls the cursor's :meth:`executescript` method
253   with the parameters given.
254
255
n256-.. method:: XXX Class.create_function(name, num_params, func)
n276+.. method:: Connection.create_function(name, num_params, func)
257
258   Creates a user-defined function that you can later use from within SQL
259   statements under the function name *name*. *num_params* is the number of
260   parameters the function accepts, and *func* is a Python callable that is called
261   as the SQL function.
262
263   The function can return any of the types supported by SQLite: unicode, str, int,
264   long, float, buffer and None.
265
266   Example:
267
n268- 
269-   .. include:: ../includes/sqlite3/md5func.py
288+   .. literalinclude:: ../includes/sqlite3/md5func.py
270-      :literal:
271
272
n273-.. method:: XXX Class.create_aggregate(name, num_params, aggregate_class)
n291+.. method:: Connection.create_aggregate(name, num_params, aggregate_class)
274
275   Creates a user-defined aggregate function.
276
277   The aggregate class must implement a ``step`` method, which accepts the number
278   of parameters *num_params*, and a ``finalize`` method which will return the
279   final result of the aggregate.
280
281   The ``finalize`` method can return any of the types supported by SQLite:
282   unicode, str, int, long, float, buffer and None.
283
284   Example:
285
n286- 
287-   .. include:: ../includes/sqlite3/mysumaggr.py
304+   .. literalinclude:: ../includes/sqlite3/mysumaggr.py
288-      :literal:
289
290
n291-.. method:: XXX Class.create_collation(name, callable)
n307+.. method:: Connection.create_collation(name, callable)
292
293   Creates a collation with the specified *name* and *callable*. The callable will
294   be passed two string arguments. It should return -1 if the first is ordered
295   lower than the second, 0 if they are ordered equal and 1 if the first is ordered
296   higher than the second.  Note that this controls sorting (ORDER BY in SQL) so
297   your comparisons don't affect other SQL operations.
298
299   Note that the callable will get its parameters as Python bytestrings, which will
300   normally be encoded in UTF-8.
301
302   The following example shows a custom collation that sorts "the wrong way":
303
n304- 
305-   .. include:: ../includes/sqlite3/collation_reverse.py
320+   .. literalinclude:: ../includes/sqlite3/collation_reverse.py
306-      :literal:
307
308   To remove a collation, call ``create_collation`` with None as callable::
309
310      con.create_collation("reverse", None)
311
312
n313-.. method:: XXX Class.interrupt()
n327+.. method:: Connection.interrupt()
314
315   You can call this method from a different thread to abort any queries that might
316   be executing on the connection. The query will then abort and the caller will
317   get an exception.
318
319
n320-.. method:: XXX Class.set_authorizer(authorizer_callback)
n334+.. method:: Connection.set_authorizer(authorizer_callback)
321
322   This routine registers a callback. The callback is invoked for each attempt to
323   access a column of a table in the database. The callback should return
324   :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
325   statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
326   column should be treated as a NULL value. These constants are available in the
327   :mod:`sqlite3` module.
328
329   The first argument to the callback signifies what kind of operation is to be
330   authorized. The second and third argument will be arguments or :const:`None`
331   depending on the first argument. The 4th argument is the name of the database
n332-   ("main", "temp", etc.) if applicable. The 5th argument is the name of the inner-
n346+   ("main", "temp", etc.) if applicable. The 5th argument is the name of the
333-   most trigger or view that is responsible for the access attempt or :const:`None`
347+   inner-most trigger or view that is responsible for the access attempt or
334-   if this access attempt is directly from input SQL code.
348+   :const:`None` if this access attempt is directly from input SQL code.
335
336   Please consult the SQLite documentation about the possible values for the first
337   argument and the meaning of the second and third argument depending on the first
338   one. All necessary constants are available in the :mod:`sqlite3` module.
339
340
n355+.. method:: Connection.set_progress_handler(handler, n)
356+ 
357+   .. versionadded:: 2.6
358+ 
359+   This routine registers a callback. The callback is invoked for every *n*
360+   instructions of the SQLite virtual machine. This is useful if you want to
361+   get called from SQLite during long-running operations, for example to update
362+   a GUI.
363+ 
364+   If you want to clear any previously installed progress handler, call the
365+   method with :const:`None` for *handler*.
366+ 
367+ 
341-.. attribute:: XXX Class.row_factory
368+.. attribute:: Connection.row_factory
342
343   You can change this attribute to a callable that accepts the cursor and the
344   original row as a tuple and will return the real result row.  This way, you can
345   implement more advanced ways of returning results, such  as returning an object
346   that can also access columns by name.
347
348   Example:
349
n350- 
351-   .. include:: ../includes/sqlite3/row_factory.py
377+   .. literalinclude:: ../includes/sqlite3/row_factory.py
352-      :literal:
353
n354-   If returning a tuple doesn't suffice and you want name-based access to columns,
n379+   If returning a tuple doesn't suffice and you want name-based access to
355-   you should consider setting :attr:`row_factory` to the highly-optimized
380+   columns, you should consider setting :attr:`row_factory` to the
356-   :class:`sqlite3.Row` type. :class:`Row` provides both index-based and case-
381+   highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
357-   insensitive name-based access to columns with almost no memory overhead. It will
382+   index-based and case-insensitive name-based access to columns with almost no
358-   probably be better than your own custom  dictionary-based approach or even a
383+   memory overhead. It will probably be better than your own custom
359-   db_row based solution.
384+   dictionary-based approach or even a db_row based solution.
360
n361-   .. % XXX what's a db_row-based solution?
n386+   .. XXX what's a db_row-based solution?
362
363
n364-.. attribute:: XXX Class.text_factory
n389+.. attribute:: Connection.text_factory
365
n366-   Using this attribute you can control what objects are returned for the TEXT data
n391+   Using this attribute you can control what objects are returned for the ``TEXT``
367-   type. By default, this attribute is set to :class:`unicode` and the
392+   data type. By default, this attribute is set to :class:`unicode` and the
368-   :mod:`sqlite3` module will return Unicode objects for TEXT. If you want to
393+   :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
369   return bytestrings instead, you can set it to :class:`str`.
370
371   For efficiency reasons, there's also a way to return Unicode objects only for
372   non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to
373   :const:`sqlite3.OptimizedUnicode`.
374
375   You can also set it to any other callable that accepts a single bytestring
376   parameter and returns the resulting object.
377
378   See the following example code for illustration:
379
n380- 
381-   .. include:: ../includes/sqlite3/text_factory.py
405+   .. literalinclude:: ../includes/sqlite3/text_factory.py
382-      :literal:
383
384
n385-.. attribute:: XXX Class.total_changes
n408+.. attribute:: Connection.total_changes
386
387   Returns the total number of database rows that have been modified, inserted, or
388   deleted since the database connection was opened.
389
390
n414+.. attribute:: Connection.iterdump
415+ 
416+   Returns an iterator to dump the database in an SQL text format.  Useful when
417+   saving an in-memory database for later restoration.  This function provides
418+   the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
419+   shell.
420+ 
421+   .. versionadded:: 2.6
422+ 
423+   Example::
424+ 
425+      # Convert file existing_db.db to SQL dump file dump.sql
426+      import sqlite3, os
427+ 
428+      con = sqlite3.connect('existing_db.db')
429+      with open('dump.sql', 'w') as f:
430+          for line in con.iterdump():
431+              f.write('%s\n' % line)
432+ 
433+ 
391.. _sqlite3-cursor-objects:
392
393Cursor Objects
394--------------
395
n396-A :class:`Cursor` instance has the following attributes and methods:
n439+.. class:: Cursor
397
n441+   A SQLite database cursor has the following attributes and methods:
398
n399-.. method:: XXX Class.execute(sql, [parameters])
n443+.. method:: Cursor.execute(sql, [parameters])
400
n401-   Executes a SQL statement. The SQL statement may be parametrized (i. e.
n445+   Executes an SQL statement. The SQL statement may be parametrized (i. e.
402   placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
403   kinds of placeholders: question marks (qmark style) and named placeholders
404   (named style).
405
406   This example shows how to use parameters with qmark style:
407
n408- 
409-   .. include:: ../includes/sqlite3/execute_1.py
452+   .. literalinclude:: ../includes/sqlite3/execute_1.py
410-      :literal:
411
412   This example shows how to use the named style:
413
n414- 
415-   .. include:: ../includes/sqlite3/execute_2.py
456+   .. literalinclude:: ../includes/sqlite3/execute_2.py
416-      :literal:
417
418   :meth:`execute` will only execute a single SQL statement. If you try to execute
419   more than one statement with it, it will raise a Warning. Use
420   :meth:`executescript` if you want to execute multiple SQL statements with one
421   call.
422
423
n424-.. method:: XXX Class.executemany(sql, seq_of_parameters)
n464+.. method:: Cursor.executemany(sql, seq_of_parameters)
425
n426-   Executes a SQL command against all parameter sequences or mappings found in the
n466+   Executes an SQL command against all parameter sequences or mappings found in
427-   sequence *sql*. The :mod:`sqlite3` module also allows using an iterator yielding
467+   the sequence *sql*.  The :mod:`sqlite3` module also allows using an
428-   parameters instead of a sequence.
468+   :term:`iterator` yielding parameters instead of a sequence.
429
n430- 
431-   .. include:: ../includes/sqlite3/executemany_1.py
470+   .. literalinclude:: ../includes/sqlite3/executemany_1.py
432-      :literal:
433
n434-   Here's a shorter example using a generator:
n472+   Here's a shorter example using a :term:`generator`:
435
n436- 
437-   .. include:: ../includes/sqlite3/executemany_2.py
474+   .. literalinclude:: ../includes/sqlite3/executemany_2.py
438-      :literal:
439
440
n441-.. method:: XXX Class.executescript(sql_script)
n477+.. method:: Cursor.executescript(sql_script)
442
443   This is a nonstandard convenience method for executing multiple SQL statements
n444-   at once. It issues a COMMIT statement first, then executes the SQL script it
n480+   at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
445   gets as a parameter.
446
447   *sql_script* can be a bytestring or a Unicode string.
448
449   Example:
450
n451- 
452-   .. include:: ../includes/sqlite3/executescript.py
487+   .. literalinclude:: ../includes/sqlite3/executescript.py
453-      :literal:
454
455
n490+.. method:: Cursor.fetchone()
491+ 
492+   Fetches the next row of a query result set, returning a single sequence,
493+   or :const:`None` when no more data is available.
494+ 
495+ 
496+.. method:: Cursor.fetchmany([size=cursor.arraysize])
497+ 
498+   Fetches the next set of rows of a query result, returning a list.  An empty
499+   list is returned when no more rows are available.
500+ 
501+   The number of rows to fetch per call is specified by the *size* parameter.
502+   If it is not given, the cursor's arraysize determines the number of rows
503+   to be fetched. The method should try to fetch as many rows as indicated by
504+   the size parameter. If this is not possible due to the specified number of
505+   rows not being available, fewer rows may be returned.
506+ 
507+   Note there are performance considerations involved with the *size* parameter.
508+   For optimal performance, it is usually best to use the arraysize attribute.
509+   If the *size* parameter is used, then it is best for it to retain the same
510+   value from one :meth:`fetchmany` call to the next.
511+ 
512+.. method:: Cursor.fetchall()
513+ 
514+   Fetches all (remaining) rows of a query result, returning a list.  Note that
515+   the cursor's arraysize attribute can affect the performance of this operation.
516+   An empty list is returned when no rows are available.
517+ 
518+ 
456-.. attribute:: XXX Class.rowcount
519+.. attribute:: Cursor.rowcount
457
458   Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
459   attribute, the database engine's own support for the determination of "rows
460   affected"/"rows selected" is quirky.
461
n462-   For ``SELECT`` statements, :attr:`rowcount` is always None because we cannot
463-   determine the number of rows a query produced until all rows were fetched.
464- 
465   For ``DELETE`` statements, SQLite reports :attr:`rowcount` as 0 if you make a
466   ``DELETE FROM table`` without any condition.
467
468   For :meth:`executemany` statements, the number of modifications are summed up
469   into :attr:`rowcount`.
470
471   As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
n472-   case no executeXX() has been performed on the cursor or the rowcount of the last
n532+   case no ``executeXX()`` has been performed on the cursor or the rowcount of the
473-   operation is not determinable by the interface".
533+   last operation is not determinable by the interface".
534+ 
535+   This includes ``SELECT`` statements because we cannot determine the number of
536+   rows a query produced until all rows were fetched.
537+ 
538+.. attribute:: Cursor.lastrowid
539+ 
540+   This read-only attribute provides the rowid of the last modified row. It is
541+   only set if you issued a ``INSERT`` statement using the :meth:`execute`
542+   method. For operations other than ``INSERT`` or when :meth:`executemany` is
543+   called, :attr:`lastrowid` is set to :const:`None`.
544+ 
545+.. attribute:: Cursor.description
546+ 
547+   This read-only attribute provides the column names of the last query. To
548+   remain compatible with the Python DB API, it returns a 7-tuple for each
549+   column where the last six items of each tuple are :const:`None`.
550+ 
551+   It is set for ``SELECT`` statements without any matching rows as well.
552+ 
553+.. _sqlite3-row-objects:
554+ 
555+Row Objects
556+-----------
557+ 
558+.. class:: Row
559+ 
560+   A :class:`Row` instance serves as a highly optimized
561+   :attr:`~Connection.row_factory` for :class:`Connection` objects.
562+   It tries to mimic a tuple in most of its features.
563+ 
564+   It supports mapping access by column name and index, iteration,
565+   representation, equality testing and :func:`len`.
566+ 
567+   If two :class:`Row` objects have exactly the same columns and their
568+   members are equal, they compare equal.
569+ 
570+   .. versionchanged:: 2.6
571+      Added iteration and equality (hashability).
572+ 
573+   .. method:: keys
574+ 
575+      This method returns a tuple of column names. Immediately after a query,
576+      it is the first member of each tuple in :attr:`Cursor.description`.
577+ 
578+      .. versionadded:: 2.6
579+ 
580+Let's assume we initialize a table as in the example given above::
581+ 
582+    conn = sqlite3.connect(":memory:")
583+    c = conn.cursor()
584+    c.execute('''create table stocks
585+    (date text, trans text, symbol text,
586+     qty real, price real)''')
587+    c.execute("""insert into stocks
588+              values ('2006-01-05','BUY','RHAT',100,35.14)""")
589+    conn.commit()
590+    c.close()
591+ 
592+Now we plug :class:`Row` in::
593+ 
594+    >>> conn.row_factory = sqlite3.Row
595+    >>> c = conn.cursor()
596+    >>> c.execute('select * from stocks')
597+    <sqlite3.Cursor object at 0x7f4e7dd8fa80>
598+    >>> r = c.fetchone()
599+    >>> type(r)
600+    <type 'sqlite3.Row'>
601+    >>> r
602+    (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)
603+    >>> len(r)
604+    5
605+    >>> r[2]
606+    u'RHAT'
607+    >>> r.keys()
608+    ['date', 'trans', 'symbol', 'qty', 'price']
609+    >>> r['qty']
610+    100.0
611+    >>> for member in r: print member
612+    ...
613+    2006-01-05
614+    BUY
615+    RHAT
616+    100.0
617+    35.14
474
475
476.. _sqlite3-types:
477
478SQLite and Python types
479-----------------------
480
481
482Introduction
483^^^^^^^^^^^^
484
n485-SQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB.
n629+SQLite natively supports the following types: ``NULL````INTEGER``,
630+``REAL``, ``TEXT``, ``BLOB``.
486
487The following Python types can thus be sent to SQLite without any problem:
488
n489-+------------------------+-------------+
n634++-----------------------------+-------------+
490-| Python type            | SQLite type |
635+| Python type                 | SQLite type |
491-+========================+=============+
636++=============================+=============+
492-| ``None``               | NULL        |
637+| :const:`None`               | ``NULL``    |
493-+------------------------+-------------+
638++-----------------------------+-------------+
494-| ``int``                | INTEGER     |
639+| :class:`int`                | ``INTEGER`` |
495-+------------------------+-------------+
640++-----------------------------+-------------+
496-| ``long``               | INTEGER     |
641+| :class:`long`               | ``INTEGER`` |
497-+------------------------+-------------+
642++-----------------------------+-------------+
498-| ``float``              | REAL        |
643+| :class:`float`              | ``REAL``    |
499-+------------------------+-------------+
644++-----------------------------+-------------+
500-``str (UTF8-encoded)`` | TEXT        |
645+:class:`str` (UTF8-encoded) | ``TEXT``    |
501-+------------------------+-------------+
646++-----------------------------+-------------+
502-| ``unicode``            | TEXT        |
647+| :class:`unicode`            | ``TEXT``    |
503-+------------------------+-------------+
648++-----------------------------+-------------+
504-| ``buffer``             | BLOB        |
649+| :class:`buffer`             | ``BLOB``    |
505-+------------------------+-------------+
650++-----------------------------+-------------+
506
507This is how SQLite types are converted to Python types by default:
508
n509-+-------------+---------------------------------------------+
n654++-------------+----------------------------------------------+
510-| SQLite type | Python type                                 |
655+| SQLite type | Python type                                  |
511-+=============+=============================================+
656++=============+==============================================+
512-| ``NULL``    | None                                        |
657+| ``NULL``    | :const:`None`                                |
513-+-------------+---------------------------------------------+
658++-------------+----------------------------------------------+
514-| ``INTEGER`` | int or long, depending on size              |
659+| ``INTEGER`` | :class:`int` or :class:`long`,               |
660+|             | depending on size                            |
515-+-------------+---------------------------------------------+
661++-------------+----------------------------------------------+
516-| ``REAL``    | float                                       |
662+| ``REAL``    | :class:`float`                               |
517-+-------------+---------------------------------------------+
663++-------------+----------------------------------------------+
518-| ``TEXT``    | depends on text_factory, unicode by default |
664+| ``TEXT``    | depends on :attr:`~Connection.text_factory`, |
665+|             | :class:`unicode` by default                  |
519-+-------------+---------------------------------------------+
666++-------------+----------------------------------------------+
520-| ``BLOB``    | buffer                                      |
667+| ``BLOB``    | :class:`buffer`                              |
521-+-------------+---------------------------------------------+
668++-------------+----------------------------------------------+
522
523The type system of the :mod:`sqlite3` module is extensible in two ways: you can
524store additional Python types in a SQLite database via object adaptation, and
525you can let the :mod:`sqlite3` module convert SQLite types to different Python
526types via converters.
527
528
529Using adapters to store additional Python types in SQLite databases
552           self.x, self.y = x, y
553
554Now you want to store the point in a single SQLite column.  First you'll have to
555choose one of the supported types first to be used for representing the point.
556Let's just use str and separate the coordinates using a semicolon. Then you need
557to give your class a method ``__conform__(self, protocol)`` which must return
558the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
559
n560- 
561-.. include:: ../includes/sqlite3/adapter_point_1.py
707+.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
562-   :literal:
563
564
565Registering an adapter callable
566"""""""""""""""""""""""""""""""
567
568The other possibility is to create a function that converts the type to the
569string representation and register the function with :meth:`register_adapter`.
570
571.. note::
572
n573-   The type/class to adapt must be a new-style class, i. e. it must have
n718+   The type/class to adapt must be a :term:`new-style class`, i. e. it must have
574   :class:`object` as one of its bases.
575
n576- 
577-.. include:: ../includes/sqlite3/adapter_point_2.py
721+.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
578-   :literal:
579
580The :mod:`sqlite3` module has two default adapters for Python's built-in
581:class:`datetime.date` and :class:`datetime.datetime` types.  Now let's suppose
582we want to store :class:`datetime.datetime` objects not in ISO representation,
583but as a Unix timestamp.
584
n585- 
586-.. include:: ../includes/sqlite3/adapter_datetime.py
728+.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
587-   :literal:
588
589
590Converting SQLite values to custom Python types
591^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
592
593Writing an adapter lets you send custom Python types to SQLite. But to make it
594really useful we need to make the Python to SQLite to Python roundtrip work.
595
600
601First, we'll define a converter function that accepts the string as a parameter
602and constructs a :class:`Point` object from it.
603
604.. note::
605
606   Converter functions **always** get called with a string, no matter under which
607   data type you sent the value to SQLite.
n608- 
609-.. note::
610- 
611-   Converter names are looked up in a case-sensitive manner.
612
613::
614
615   def convert_point(s):
616       x, y = map(float, s.split(";"))
617       return Point(x, y)
618
619Now you need to make the :mod:`sqlite3` module know that what you select from
620the database is actually a point. There are two ways of doing this:
621
622* Implicitly via the declared type
623
624* Explicitly via the column name
625
n626-Both ways are described in "Module Constants", section
n763+Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
627-:ref:`sqlite3-module-contents`, in the entries for the constants
628-:const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
764+for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
629
630The following example illustrates both approaches.
631
n632- 
633-.. include:: ../includes/sqlite3/converter_point.py
768+.. literalinclude:: ../includes/sqlite3/converter_point.py
634-   :literal:
635
636
637Default adapters and converters
638^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
639
640There are default adapters for the date and datetime types in the datetime
641module. They will be sent as ISO dates/ISO timestamps to SQLite.
642
645:class:`datetime.datetime`.
646
647This way, you can use date/timestamps from Python without any additional
648fiddling in most cases. The format of the adapters is also compatible with the
649experimental SQLite date/time functions.
650
651The following example demonstrates this.
652
n653- 
654-.. include:: ../includes/sqlite3/pysqlite_datetime.py
787+.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
655-   :literal:
656
657
658.. _sqlite3-controlling-transactions:
659
660Controlling Transactions
661------------------------
662
663By default, the :mod:`sqlite3` module opens transactions implicitly before a
n664-Data Modification Language (DML)  statement (i.e. INSERT/UPDATE/DELETE/REPLACE),
n796+Data Modification Language (DML)  statement (i.e.
797+``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
665-and commits transactions implicitly before a non-DML, non-query statement (i. e.
798+implicitly before a non-DML, non-query statement (i. e.
666-anything other than SELECT/INSERT/UPDATE/DELETE/REPLACE).
799+anything other than ``SELECT`` or the aforementioned).
667
668So if you are within a transaction and issue a command like ``CREATE TABLE
669...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
670before executing that command. There are two reasons for doing that. The first
671is that some of these commands don't work within transactions. The other reason
672is that pysqlite needs to keep track of the transaction state (if a transaction
673is active or not).
674
n675-You can control which kind of "BEGIN" statements pysqlite implicitly executes
n808+You can control which kind of ``BEGIN`` statements pysqlite implicitly executes
676(or none at all) via the *isolation_level* parameter to the :func:`connect`
677call, or via the :attr:`isolation_level` property of connections.
678
679If you want **autocommit mode**, then set :attr:`isolation_level` to None.
680
681Otherwise leave it at its default, which will result in a plain "BEGIN"
n682-statement, or set it to one of SQLite's supported isolation levels: DEFERRED,
n815+statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
683-IMMEDIATE or EXCLUSIVE.
816+"IMMEDIATE" or "EXCLUSIVE".
684
n685-As the :mod:`sqlite3` module needs to keep track of the transaction state, you
686-should not use ``OR ROLLBACK`` or ``ON CONFLICT ROLLBACK`` in your SQL. Instead,
687-catch the :exc:`IntegrityError` and call the :meth:`rollback` method of the
688-connection yourself.
689
690
691Using pysqlite efficiently
692--------------------------
693
694
695Using shortcut methods
696^^^^^^^^^^^^^^^^^^^^^^
697
698Using the nonstandard :meth:`execute`, :meth:`executemany` and
699:meth:`executescript` methods of the :class:`Connection` object, your code can
700be written more concisely because you don't have to create the (often
701superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
702objects are created implicitly and these shortcut methods return the cursor
n703-objects. This way, you can execute a SELECT statement and iterate over it
n832+objects. This way, you can execute a ``SELECT`` statement and iterate over it
704directly using only a single call on the :class:`Connection` object.
705
n706- 
707-.. include:: ../includes/sqlite3/shortcut_methods.py
835+.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
708-   :literal:
709
710
711Accessing columns by name instead of by index
712^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
713
714One useful feature of the :mod:`sqlite3` module is the builtin
715:class:`sqlite3.Row` class designed to be used as a row factory.
716
717Rows wrapped with this class can be accessed both by index (like tuples) and
718case-insensitively by name:
719
n720- 
721-.. include:: ../includes/sqlite3/rowclass.py
847+.. literalinclude:: ../includes/sqlite3/rowclass.py
722-   :literal:
723
t849+ 
850+Using the connection as a context manager
851+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
852+ 
853+.. versionadded:: 2.6
854+ 
855+Connection objects can be used as context managers
856+that automatically commit or rollback transactions.  In the event of an
857+exception, the transaction is rolled back; otherwise, the transaction is
858+committed:
859+ 
860+.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op