Debian Codegraph @

cpython27/Doc/library/sqlite3.rst

raw
1 :mod:`sqlite3` --- DB-API 2.0 interface for SQLite databases
2 ============================================================
3
4 .. module:: sqlite3
5 :synopsis: A DB-API 2.0 implementation using SQLite 3.x.
6 .. sectionauthor:: Gerhard Häring <[email protected]>
7
8
9 .. versionadded:: 2.5
10
11 SQLite is a C library that provides a lightweight disk-based database that
12 doesn't require a separate server process and allows accessing the database
13 using a nonstandard variant of the SQL query language. Some applications can use
14 SQLite for internal data storage. It's also possible to prototype an
15 application using SQLite and then port the code to a larger database such as
16 PostgreSQL or Oracle.
17
18 The sqlite3 module was written by Gerhard Häring. It provides a SQL interface
19 compliant with the DB-API 2.0 specification described by :pep:`249`.
20
21 To use the module, you must first create a :class:`Connection` object that
22 represents the database. Here the data will be stored in the
23 :file:`example.db` file::
24
25 import sqlite3
26 conn = sqlite3.connect('example.db')
27
28 You can also supply the special name ``:memory:`` to create a database in RAM.
29
30 Once you have a :class:`Connection`, you can create a :class:`Cursor` object
31 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, qty real, price real)''')
38
39 # Insert a row of data
40 c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
41
42 # Save (commit) the changes
43 conn.commit()
44
45 # We can also close the connection if we are done with it.
46 # Just be sure any changes have been committed or they will be lost.
47 conn.close()
48
49 The data you've saved is persistent and is available in subsequent sessions::
50
51 import sqlite3
52 conn = sqlite3.connect('example.db')
53 c = conn.cursor()
54
55 Usually your SQL operations will need to use values from Python variables. You
56 shouldn't assemble your query using Python's string operations because doing so
57 is insecure; it makes your program vulnerable to an SQL injection attack
58 (see https://xkcd.com/327/ for humorous example of what can go wrong).
59
60 Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
61 wherever you want to use a value, and then provide a tuple of values as the
62 second argument to the cursor's :meth:`~Cursor.execute` method. (Other database
63 modules may use a different placeholder, such as ``%s`` or ``:1``.) For
64 example::
65
66 # Never do this -- insecure!
67 symbol = 'RHAT'
68 c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
69
70 # Do this instead
71 t = ('RHAT',)
72 c.execute('SELECT * FROM stocks WHERE symbol=?', t)
73 print c.fetchone()
74
75 # Larger example that inserts many records at a time
76 purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
77 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
78 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
79 ]
80 c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
81
82 To retrieve data after executing a SELECT statement, you can either treat the
83 cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
84 retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
85 matching rows.
86
87 This example uses the iterator form::
88
89 >>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
90 print row
91
92 (u'2006-01-05', u'BUY', u'RHAT', 100, 35.14)
93 (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
94 (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
95 (u'2006-04-05', u'BUY', u'MSFT', 1000, 72.0)
96
97
98 .. seealso::
99
100 https://github.com/ghaering/pysqlite
101 The pysqlite web page -- sqlite3 is developed externally under the name
102 "pysqlite".
103
104 https://www.sqlite.org
105 The SQLite web page; the documentation describes the syntax and the
106 available data types for the supported SQL dialect.
107
108 http://www.w3schools.com/sql/
109 Tutorial, reference and examples for learning SQL syntax.
110
111 :pep:`249` - Database API Specification 2.0
112 PEP written by Marc-André Lemburg.
113
114
115 .. _sqlite3-module-contents:
116
117 Module functions and constants
118 ------------------------------
119
120
121 .. data:: version
122
123 The version number of this module, as a string. This is not the version of
124 the SQLite library.
125
126 .. data:: version_info
127
128 The version number of this module, as a tuple of integers. This is not the
129 version of the SQLite library.
130
131 .. data:: sqlite_version
132
133 The version number of the run-time SQLite library, as a string.
134
135 .. data:: sqlite_version_info
136
137 The version number of the run-time SQLite library, as a tuple of integers.
138
139 .. data:: PARSE_DECLTYPES
140
141 This constant is meant to be used with the *detect_types* parameter of the
142 :func:`connect` function.
143
144 Setting it makes the :mod:`sqlite3` module parse the declared type for each
145 column it returns. It will parse out the first word of the declared type,
146 i. e. for "integer primary key", it will parse out "integer", or for
147 "number(10)" it will parse out "number". Then for that column, it will look
148 into the converters dictionary and use the converter function registered for
149 that type there.
150
151
152 .. data:: PARSE_COLNAMES
153
154 This constant is meant to be used with the *detect_types* parameter of the
155 :func:`connect` function.
156
157 Setting this makes the SQLite interface parse the column name for each column it
158 returns. It will look for a string formed [mytype] in there, and then decide
159 that 'mytype' is the type of the column. It will try to find an entry of
160 'mytype' in the converters dictionary and then use the converter function found
161 there to return the value. The column name found in :attr:`Cursor.description`
162 is only the first word of the column name, i. e. if you use something like
163 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
164 first blank for the column name: the column name would simply be "x".
165
166
167 .. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
168
169 Opens a connection to the SQLite database file *database*. You can use
170 ``":memory:"`` to open a database connection to a database that resides in RAM
171 instead of on disk.
172
173 When a database is accessed by multiple connections, and one of the processes
174 modifies the database, the SQLite database is locked until that transaction is
175 committed. The *timeout* parameter specifies how long the connection should wait
176 for the lock to go away until raising an exception. The default for the timeout
177 parameter is 5.0 (five seconds).
178
179 For the *isolation_level* parameter, please see the
180 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
181
182 SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
183 you want to use other types you must add support for them yourself. The
184 *detect_types* parameter and the using custom **converters** registered with the
185 module-level :func:`register_converter` function allow you to easily do that.
186
187 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
188 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
189 type detection on.
190
191 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
192 connect call. You can, however, subclass the :class:`Connection` class and make
193 :func:`connect` use your class instead by providing your class for the *factory*
194 parameter.
195
196 Consult the section :ref:`sqlite3-types` of this manual for details.
197
198 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
199 overhead. If you want to explicitly set the number of statements that are cached
200 for the connection, you can set the *cached_statements* parameter. The currently
201 implemented default is to cache 100 statements.
202
203
204 .. function:: register_converter(typename, callable)
205
206 Registers a callable to convert a bytestring from the database into a custom
207 Python type. The callable will be invoked for all database values that are of
208 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
209 function for how the type detection works. Note that *typename* and the name of
210 the type in your query are matched in case-insensitive manner.
211
212
213 .. function:: register_adapter(type, callable)
214
215 Registers a callable to convert the custom Python type *type* into one of
216 SQLite's supported types. The callable *callable* accepts as single parameter
217 the Python value, and must return a value of the following types: int, long,
218 float, str (UTF-8 encoded), unicode or buffer.
219
220
221 .. function:: complete_statement(sql)
222
223 Returns :const:`True` if the string *sql* contains one or more complete SQL
224 statements terminated by semicolons. It does not verify that the SQL is
225 syntactically correct, only that there are no unclosed string literals and the
226 statement is terminated by a semicolon.
227
228 This can be used to build a shell for SQLite, as in the following example:
229
230
231 .. literalinclude:: ../includes/sqlite3/complete_statement.py
232
233
234 .. function:: enable_callback_tracebacks(flag)
235
236 By default you will not get any tracebacks in user-defined functions,
237 aggregates, converters, authorizer callbacks etc. If you want to debug them,
238 you can call this function with *flag* set to ``True``. Afterwards, you will
239 get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to
240 disable the feature again.
241
242
243 .. _sqlite3-connection-objects:
244
245 Connection Objects
246 ------------------
247
248 .. class:: Connection
249
250 A SQLite database connection has the following attributes and methods:
251
252 .. attribute:: isolation_level
253
254 Get or set the current isolation level. :const:`None` for autocommit mode or
255 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
256 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
257
258
259 .. method:: cursor(factory=Cursor)
260
261 The cursor method accepts a single optional parameter *factory*. If
262 supplied, this must be a callable returning an instance of :class:`Cursor`
263 or its subclasses.
264
265 .. method:: commit()
266
267 This method commits the current transaction. If you don't call this method,
268 anything you did since the last call to ``commit()`` is not visible from
269 other database connections. If you wonder why you don't see the data you've
270 written to the database, please check you didn't forget to call this method.
271
272 .. method:: rollback()
273
274 This method rolls back any changes to the database since the last call to
275 :meth:`commit`.
276
277 .. method:: close()
278
279 This closes the database connection. Note that this does not automatically
280 call :meth:`commit`. If you just close your database connection without
281 calling :meth:`commit` first, your changes will be lost!
282
283 .. method:: execute(sql, [parameters])
284
285 This is a nonstandard shortcut that creates an intermediate cursor object by
286 calling the cursor method, then calls the cursor's :meth:`execute
287 <Cursor.execute>` method with the parameters given.
288
289
290 .. method:: executemany(sql, [parameters])
291
292 This is a nonstandard shortcut that creates an intermediate cursor object by
293 calling the cursor method, then calls the cursor's :meth:`executemany
294 <Cursor.executemany>` method with the parameters given.
295
296 .. method:: executescript(sql_script)
297
298 This is a nonstandard shortcut that creates an intermediate cursor object by
299 calling the cursor method, then calls the cursor's :meth:`executescript
300 <Cursor.executescript>` method with the parameters given.
301
302
303 .. method:: create_function(name, num_params, func)
304
305 Creates a user-defined function that you can later use from within SQL
306 statements under the function name *name*. *num_params* is the number of
307 parameters the function accepts, and *func* is a Python callable that is called
308 as the SQL function.
309
310 The function can return any of the types supported by SQLite: unicode, str, int,
311 long, float, buffer and ``None``.
312
313 Example:
314
315 .. literalinclude:: ../includes/sqlite3/md5func.py
316
317
318 .. method:: create_aggregate(name, num_params, aggregate_class)
319
320 Creates a user-defined aggregate function.
321
322 The aggregate class must implement a ``step`` method, which accepts the number
323 of parameters *num_params*, and a ``finalize`` method which will return the
324 final result of the aggregate.
325
326 The ``finalize`` method can return any of the types supported by SQLite:
327 unicode, str, int, long, float, buffer and ``None``.
328
329 Example:
330
331 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
332
333
334 .. method:: create_collation(name, callable)
335
336 Creates a collation with the specified *name* and *callable*. The callable will
337 be passed two string arguments. It should return -1 if the first is ordered
338 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
339 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
340 your comparisons don't affect other SQL operations.
341
342 Note that the callable will get its parameters as Python bytestrings, which will
343 normally be encoded in UTF-8.
344
345 The following example shows a custom collation that sorts "the wrong way":
346
347 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
348
349 To remove a collation, call ``create_collation`` with ``None`` as callable::
350
351 con.create_collation("reverse", None)
352
353
354 .. method:: interrupt()
355
356 You can call this method from a different thread to abort any queries that might
357 be executing on the connection. The query will then abort and the caller will
358 get an exception.
359
360
361 .. method:: set_authorizer(authorizer_callback)
362
363 This routine registers a callback. The callback is invoked for each attempt to
364 access a column of a table in the database. The callback should return
365 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
366 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
367 column should be treated as a NULL value. These constants are available in the
368 :mod:`sqlite3` module.
369
370 The first argument to the callback signifies what kind of operation is to be
371 authorized. The second and third argument will be arguments or :const:`None`
372 depending on the first argument. The 4th argument is the name of the database
373 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
374 inner-most trigger or view that is responsible for the access attempt or
375 :const:`None` if this access attempt is directly from input SQL code.
376
377 Please consult the SQLite documentation about the possible values for the first
378 argument and the meaning of the second and third argument depending on the first
379 one. All necessary constants are available in the :mod:`sqlite3` module.
380
381
382 .. method:: set_progress_handler(handler, n)
383
384 This routine registers a callback. The callback is invoked for every *n*
385 instructions of the SQLite virtual machine. This is useful if you want to
386 get called from SQLite during long-running operations, for example to update
387 a GUI.
388
389 If you want to clear any previously installed progress handler, call the
390 method with :const:`None` for *handler*.
391
392 .. versionadded:: 2.6
393
394
395 .. method:: enable_load_extension(enabled)
396
397 This routine allows/disallows the SQLite engine to load SQLite extensions
398 from shared libraries. SQLite extensions can define new functions,
399 aggregates or whole new virtual table implementations. One well-known
400 extension is the fulltext-search extension distributed with SQLite.
401
402 Loadable extensions are disabled by default. See [#f1]_.
403
404 .. versionadded:: 2.7
405
406 .. literalinclude:: ../includes/sqlite3/load_extension.py
407
408 .. method:: load_extension(path)
409
410 This routine loads a SQLite extension from a shared library. You have to
411 enable extension loading with :meth:`enable_load_extension` before you can
412 use this routine.
413
414 Loadable extensions are disabled by default. See [#f1]_.
415
416 .. versionadded:: 2.7
417
418 .. attribute:: row_factory
419
420 You can change this attribute to a callable that accepts the cursor and the
421 original row as a tuple and will return the real result row. This way, you can
422 implement more advanced ways of returning results, such as returning an object
423 that can also access columns by name.
424
425 Example:
426
427 .. literalinclude:: ../includes/sqlite3/row_factory.py
428
429 If returning a tuple doesn't suffice and you want name-based access to
430 columns, you should consider setting :attr:`row_factory` to the
431 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
432 index-based and case-insensitive name-based access to columns with almost no
433 memory overhead. It will probably be better than your own custom
434 dictionary-based approach or even a db_row based solution.
435
436 .. XXX what's a db_row-based solution?
437
438
439 .. attribute:: text_factory
440
441 Using this attribute you can control what objects are returned for the ``TEXT``
442 data type. By default, this attribute is set to :class:`unicode` and the
443 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
444 return bytestrings instead, you can set it to :class:`str`.
445
446 For efficiency reasons, there's also a way to return Unicode objects only for
447 non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to
448 :const:`sqlite3.OptimizedUnicode`.
449
450 You can also set it to any other callable that accepts a single bytestring
451 parameter and returns the resulting object.
452
453 See the following example code for illustration:
454
455 .. literalinclude:: ../includes/sqlite3/text_factory.py
456
457
458 .. attribute:: total_changes
459
460 Returns the total number of database rows that have been modified, inserted, or
461 deleted since the database connection was opened.
462
463
464 .. attribute:: iterdump
465
466 Returns an iterator to dump the database in an SQL text format. Useful when
467 saving an in-memory database for later restoration. This function provides
468 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
469 shell.
470
471 .. versionadded:: 2.6
472
473 Example::
474
475 # Convert file existing_db.db to SQL dump file dump.sql
476 import sqlite3, os
477
478 con = sqlite3.connect('existing_db.db')
479 with open('dump.sql', 'w') as f:
480 for line in con.iterdump():
481 f.write('%s\n' % line)
482
483
484 .. _sqlite3-cursor-objects:
485
486 Cursor Objects
487 --------------
488
489 .. class:: Cursor
490
491 A :class:`Cursor` instance has the following attributes and methods.
492
493 .. method:: execute(sql, [parameters])
494
495 Executes an SQL statement. The SQL statement may be parameterized (i. e.
496 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
497 kinds of placeholders: question marks (qmark style) and named placeholders
498 (named style).
499
500 Here's an example of both styles:
501
502 .. literalinclude:: ../includes/sqlite3/execute_1.py
503
504 :meth:`execute` will only execute a single SQL statement. If you try to execute
505 more than one statement with it, it will raise a Warning. Use
506 :meth:`executescript` if you want to execute multiple SQL statements with one
507 call.
508
509
510 .. method:: executemany(sql, seq_of_parameters)
511
512 Executes an SQL command against all parameter sequences or mappings found in
513 the sequence *sql*. The :mod:`sqlite3` module also allows using an
514 :term:`iterator` yielding parameters instead of a sequence.
515
516 .. literalinclude:: ../includes/sqlite3/executemany_1.py
517
518 Here's a shorter example using a :term:`generator`:
519
520 .. literalinclude:: ../includes/sqlite3/executemany_2.py
521
522
523 .. method:: executescript(sql_script)
524
525 This is a nonstandard convenience method for executing multiple SQL statements
526 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
527 gets as a parameter.
528
529 *sql_script* can be a bytestring or a Unicode string.
530
531 Example:
532
533 .. literalinclude:: ../includes/sqlite3/executescript.py
534
535
536 .. method:: fetchone()
537
538 Fetches the next row of a query result set, returning a single sequence,
539 or :const:`None` when no more data is available.
540
541
542 .. method:: fetchmany([size=cursor.arraysize])
543
544 Fetches the next set of rows of a query result, returning a list. An empty
545 list is returned when no more rows are available.
546
547 The number of rows to fetch per call is specified by the *size* parameter.
548 If it is not given, the cursor's arraysize determines the number of rows
549 to be fetched. The method should try to fetch as many rows as indicated by
550 the size parameter. If this is not possible due to the specified number of
551 rows not being available, fewer rows may be returned.
552
553 Note there are performance considerations involved with the *size* parameter.
554 For optimal performance, it is usually best to use the arraysize attribute.
555 If the *size* parameter is used, then it is best for it to retain the same
556 value from one :meth:`fetchmany` call to the next.
557
558 .. method:: fetchall()
559
560 Fetches all (remaining) rows of a query result, returning a list. Note that
561 the cursor's arraysize attribute can affect the performance of this operation.
562 An empty list is returned when no rows are available.
563
564
565 .. attribute:: rowcount
566
567 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
568 attribute, the database engine's own support for the determination of "rows
569 affected"/"rows selected" is quirky.
570
571 For :meth:`executemany` statements, the number of modifications are summed up
572 into :attr:`rowcount`.
573
574 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
575 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
576 last operation is not determinable by the interface". This includes ``SELECT``
577 statements because we cannot determine the number of rows a query produced
578 until all rows were fetched.
579
580 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
581 you make a ``DELETE FROM table`` without any condition.
582
583 .. attribute:: lastrowid
584
585 This read-only attribute provides the rowid of the last modified row. It is
586 only set if you issued an ``INSERT`` statement using the :meth:`execute`
587 method. For operations other than ``INSERT`` or when :meth:`executemany` is
588 called, :attr:`lastrowid` is set to :const:`None`.
589
590 .. attribute:: description
591
592 This read-only attribute provides the column names of the last query. To
593 remain compatible with the Python DB API, it returns a 7-tuple for each
594 column where the last six items of each tuple are :const:`None`.
595
596 It is set for ``SELECT`` statements without any matching rows as well.
597
598 .. attribute:: connection
599
600 This read-only attribute provides the SQLite database :class:`Connection`
601 used by the :class:`Cursor` object. A :class:`Cursor` object created by
602 calling :meth:`con.cursor() <Connection.cursor>` will have a
603 :attr:`connection` attribute that refers to *con*::
604
605 >>> con = sqlite3.connect(":memory:")
606 >>> cur = con.cursor()
607 >>> cur.connection == con
608 True
609
610 .. _sqlite3-row-objects:
611
612 Row Objects
613 -----------
614
615 .. class:: Row
616
617 A :class:`Row` instance serves as a highly optimized
618 :attr:`~Connection.row_factory` for :class:`Connection` objects.
619 It tries to mimic a tuple in most of its features.
620
621 It supports mapping access by column name and index, iteration,
622 representation, equality testing and :func:`len`.
623
624 If two :class:`Row` objects have exactly the same columns and their
625 members are equal, they compare equal.
626
627 .. versionchanged:: 2.6
628 Added iteration and equality (hashability).
629
630 .. method:: keys
631
632 This method returns a list of column names. Immediately after a query,
633 it is the first member of each tuple in :attr:`Cursor.description`.
634
635 .. versionadded:: 2.6
636
637 Let's assume we initialize a table as in the example given above::
638
639 conn = sqlite3.connect(":memory:")
640 c = conn.cursor()
641 c.execute('''create table stocks
642 (date text, trans text, symbol text,
643 qty real, price real)''')
644 c.execute("""insert into stocks
645 values ('2006-01-05','BUY','RHAT',100,35.14)""")
646 conn.commit()
647 c.close()
648
649 Now we plug :class:`Row` in::
650
651 >>> conn.row_factory = sqlite3.Row
652 >>> c = conn.cursor()
653 >>> c.execute('select * from stocks')
654 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
655 >>> r = c.fetchone()
656 >>> type(r)
657 <type 'sqlite3.Row'>
658 >>> r
659 (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
660 >>> len(r)
661 5
662 >>> r[2]
663 u'RHAT'
664 >>> r.keys()
665 ['date', 'trans', 'symbol', 'qty', 'price']
666 >>> r['qty']
667 100.0
668 >>> for member in r:
669 ... print member
670 ...
671 2006-01-05
672 BUY
673 RHAT
674 100.0
675 35.14
676
677
678 .. _sqlite3-types:
679
680 SQLite and Python types
681 -----------------------
682
683
684 Introduction
685 ^^^^^^^^^^^^
686
687 SQLite natively supports the following types: ``NULL``, ``INTEGER``,
688 ``REAL``, ``TEXT``, ``BLOB``.
689
690 The following Python types can thus be sent to SQLite without any problem:
691
692 +-----------------------------+-------------+
693 | Python type | SQLite type |
694 +=============================+=============+
695 | :const:`None` | ``NULL`` |
696 +-----------------------------+-------------+
697 | :class:`int` | ``INTEGER`` |
698 +-----------------------------+-------------+
699 | :class:`long` | ``INTEGER`` |
700 +-----------------------------+-------------+
701 | :class:`float` | ``REAL`` |
702 +-----------------------------+-------------+
703 | :class:`str` (UTF8-encoded) | ``TEXT`` |
704 +-----------------------------+-------------+
705 | :class:`unicode` | ``TEXT`` |
706 +-----------------------------+-------------+
707 | :class:`buffer` | ``BLOB`` |
708 +-----------------------------+-------------+
709
710 This is how SQLite types are converted to Python types by default:
711
712 +-------------+----------------------------------------------+
713 | SQLite type | Python type |
714 +=============+==============================================+
715 | ``NULL`` | :const:`None` |
716 +-------------+----------------------------------------------+
717 | ``INTEGER`` | :class:`int` or :class:`long`, |
718 | | depending on size |
719 +-------------+----------------------------------------------+
720 | ``REAL`` | :class:`float` |
721 +-------------+----------------------------------------------+
722 | ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
723 | | :class:`unicode` by default |
724 +-------------+----------------------------------------------+
725 | ``BLOB`` | :class:`buffer` |
726 +-------------+----------------------------------------------+
727
728 The type system of the :mod:`sqlite3` module is extensible in two ways: you can
729 store additional Python types in a SQLite database via object adaptation, and
730 you can let the :mod:`sqlite3` module convert SQLite types to different Python
731 types via converters.
732
733
734 Using adapters to store additional Python types in SQLite databases
735 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
736
737 As described before, SQLite supports only a limited set of types natively. To
738 use other Python types with SQLite, you must **adapt** them to one of the
739 sqlite3 module's supported types for SQLite: one of NoneType, int, long, float,
740 str, unicode, buffer.
741
742 There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
743 type to one of the supported ones.
744
745
746 Letting your object adapt itself
747 """"""""""""""""""""""""""""""""
748
749 This is a good approach if you write the class yourself. Let's suppose you have
750 a class like this::
751
752 class Point(object):
753 def __init__(self, x, y):
754 self.x, self.y = x, y
755
756 Now you want to store the point in a single SQLite column. First you'll have to
757 choose one of the supported types first to be used for representing the point.
758 Let's just use str and separate the coordinates using a semicolon. Then you need
759 to give your class a method ``__conform__(self, protocol)`` which must return
760 the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
761
762 .. literalinclude:: ../includes/sqlite3/adapter_point_1.py
763
764
765 Registering an adapter callable
766 """""""""""""""""""""""""""""""
767
768 The other possibility is to create a function that converts the type to the
769 string representation and register the function with :meth:`register_adapter`.
770
771 .. note::
772
773 The type/class to adapt must be a :term:`new-style class`, i. e. it must have
774 :class:`object` as one of its bases.
775
776 .. literalinclude:: ../includes/sqlite3/adapter_point_2.py
777
778 The :mod:`sqlite3` module has two default adapters for Python's built-in
779 :class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
780 we want to store :class:`datetime.datetime` objects not in ISO representation,
781 but as a Unix timestamp.
782
783 .. literalinclude:: ../includes/sqlite3/adapter_datetime.py
784
785
786 Converting SQLite values to custom Python types
787 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
788
789 Writing an adapter lets you send custom Python types to SQLite. But to make it
790 really useful we need to make the Python to SQLite to Python roundtrip work.
791
792 Enter converters.
793
794 Let's go back to the :class:`Point` class. We stored the x and y coordinates
795 separated via semicolons as strings in SQLite.
796
797 First, we'll define a converter function that accepts the string as a parameter
798 and constructs a :class:`Point` object from it.
799
800 .. note::
801
802 Converter functions **always** get called with a string, no matter under which
803 data type you sent the value to SQLite.
804
805 ::
806
807 def convert_point(s):
808 x, y = map(float, s.split(";"))
809 return Point(x, y)
810
811 Now you need to make the :mod:`sqlite3` module know that what you select from
812 the database is actually a point. There are two ways of doing this:
813
814 * Implicitly via the declared type
815
816 * Explicitly via the column name
817
818 Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
819 for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
820
821 The following example illustrates both approaches.
822
823 .. literalinclude:: ../includes/sqlite3/converter_point.py
824
825
826 Default adapters and converters
827 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
828
829 There are default adapters for the date and datetime types in the datetime
830 module. They will be sent as ISO dates/ISO timestamps to SQLite.
831
832 The default converters are registered under the name "date" for
833 :class:`datetime.date` and under the name "timestamp" for
834 :class:`datetime.datetime`.
835
836 This way, you can use date/timestamps from Python without any additional
837 fiddling in most cases. The format of the adapters is also compatible with the
838 experimental SQLite date/time functions.
839
840 The following example demonstrates this.
841
842 .. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
843
844 If a timestamp stored in SQLite has a fractional part longer than 6
845 numbers, its value will be truncated to microsecond precision by the
846 timestamp converter.
847
848
849 .. _sqlite3-controlling-transactions:
850
851 Controlling Transactions
852 ------------------------
853
854 By default, the :mod:`sqlite3` module opens transactions implicitly before a
855 Data Modification Language (DML) statement (i.e.
856 ``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
857 implicitly before a non-DML, non-query statement (i. e.
858 anything other than ``SELECT`` or the aforementioned).
859
860 So if you are within a transaction and issue a command like ``CREATE TABLE
861 ...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
862 before executing that command. There are two reasons for doing that. The first
863 is that some of these commands don't work within transactions. The other reason
864 is that sqlite3 needs to keep track of the transaction state (if a transaction
865 is active or not).
866
867 You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
868 (or none at all) via the *isolation_level* parameter to the :func:`connect`
869 call, or via the :attr:`isolation_level` property of connections.
870
871 If you want **autocommit mode**, then set :attr:`isolation_level` to ``None``.
872
873 Otherwise leave it at its default, which will result in a plain "BEGIN"
874 statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
875 "IMMEDIATE" or "EXCLUSIVE".
876
877
878
879 Using :mod:`sqlite3` efficiently
880 --------------------------------
881
882
883 Using shortcut methods
884 ^^^^^^^^^^^^^^^^^^^^^^
885
886 Using the nonstandard :meth:`execute`, :meth:`executemany` and
887 :meth:`executescript` methods of the :class:`Connection` object, your code can
888 be written more concisely because you don't have to create the (often
889 superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
890 objects are created implicitly and these shortcut methods return the cursor
891 objects. This way, you can execute a ``SELECT`` statement and iterate over it
892 directly using only a single call on the :class:`Connection` object.
893
894 .. literalinclude:: ../includes/sqlite3/shortcut_methods.py
895
896
897 Accessing columns by name instead of by index
898 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
899
900 One useful feature of the :mod:`sqlite3` module is the built-in
901 :class:`sqlite3.Row` class designed to be used as a row factory.
902
903 Rows wrapped with this class can be accessed both by index (like tuples) and
904 case-insensitively by name:
905
906 .. literalinclude:: ../includes/sqlite3/rowclass.py
907
908
909 Using the connection as a context manager
910 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
911
912 .. versionadded:: 2.6
913
914 Connection objects can be used as context managers
915 that automatically commit or rollback transactions. In the event of an
916 exception, the transaction is rolled back; otherwise, the transaction is
917 committed:
918
919 .. literalinclude:: ../includes/sqlite3/ctx_manager.py
920
921
922 Common issues
923 -------------
924
925 Multithreading
926 ^^^^^^^^^^^^^^
927
928 Older SQLite versions had issues with sharing connections between threads.
929 That's why the Python module disallows sharing connections and cursors between
930 threads. If you still try to do so, you will get an exception at runtime.
931
932 The only exception is calling the :meth:`~Connection.interrupt` method, which
933 only makes sense to call from a different thread.
934
935 .. rubric:: Footnotes
936
937 .. [#f1] The sqlite3 module is not built with loadable extension support by
938 default, because some platforms (notably Mac OS X) have SQLite libraries
939 which are compiled without this feature. To get loadable extension support,
940 you must modify setup.py and remove the line that sets
941 SQLITE_OMIT_LOAD_EXTENSION.
942