blob: baf12e8a9a6be942ba9a474664fabf99a9cb7718 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`sqlite3` --- DB-API 2.0 interface for SQLite databases
2============================================================
3
4.. module:: sqlite3
5 :synopsis: A DB-API 2.0 implementation using SQLite 3.x.
6.. sectionauthor:: Gerhard Häring <gh@ghaering.de>
7
8
Georg Brandl116aa622007-08-15 14:28:22 +00009SQLite is a C library that provides a lightweight disk-based database that
10doesn't require a separate server process and allows accessing the database
11using a nonstandard variant of the SQL query language. Some applications can use
12SQLite for internal data storage. It's also possible to prototype an
13application using SQLite and then port the code to a larger database such as
14PostgreSQL or Oracle.
15
16pysqlite was written by Gerhard Häring and provides a SQL interface compliant
17with the DB-API 2.0 specification described by :pep:`249`.
18
19To use the module, you must first create a :class:`Connection` object that
20represents the database. Here the data will be stored in the
21:file:`/tmp/example` file::
22
23 conn = sqlite3.connect('/tmp/example')
24
25You can also supply the special name ``:memory:`` to create a database in RAM.
26
27Once you have a :class:`Connection`, you can create a :class:`Cursor` object
28and call its :meth:`execute` method to perform SQL commands::
29
30 c = conn.cursor()
31
32 # Create table
33 c.execute('''create table stocks
34 (date text, trans text, symbol text,
35 qty real, price real)''')
36
37 # Insert a row of data
38 c.execute("""insert into stocks
39 values ('2006-01-05','BUY','RHAT',100,35.14)""")
40
41 # Save (commit) the changes
42 conn.commit()
43
44 # We can also close the cursor if we are done with it
45 c.close()
46
47Usually your SQL operations will need to use values from Python variables. You
48shouldn't assemble your query using Python's string operations because doing so
49is insecure; it makes your program vulnerable to an SQL injection attack.
50
51Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
52wherever you want to use a value, and then provide a tuple of values as the
53second argument to the cursor's :meth:`execute` method. (Other database modules
54may use a different placeholder, such as ``%s`` or ``:1``.) For example::
55
56 # Never do this -- insecure!
57 symbol = 'IBM'
58 c.execute("... where symbol = '%s'" % symbol)
59
60 # Do this instead
61 t = (symbol,)
62 c.execute('select * from stocks where symbol=?', t)
63
64 # Larger example
65 for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
66 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
67 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
68 ):
69 c.execute('insert into stocks values (?,?,?,?,?)', t)
70
Georg Brandl9afde1c2007-11-01 20:32:30 +000071To retrieve data after executing a SELECT statement, you can either treat the
72cursor as an :term:`iterator`, call the cursor's :meth:`fetchone` method to
73retrieve a single matching row, or call :meth:`fetchall` to get a list of the
74matching rows.
Georg Brandl116aa622007-08-15 14:28:22 +000075
76This example uses the iterator form::
77
78 >>> c = conn.cursor()
79 >>> c.execute('select * from stocks order by price')
80 >>> for row in c:
Georg Brandl6911e3c2007-09-04 07:15:32 +000081 ... print(row)
Georg Brandl116aa622007-08-15 14:28:22 +000082 ...
83 (u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
84 (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
85 (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
86 (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
87 >>>
88
89
90.. seealso::
91
92 http://www.pysqlite.org
93 The pysqlite web page.
94
95 http://www.sqlite.org
96 The SQLite web page; the documentation describes the syntax and the available
97 data types for the supported SQL dialect.
98
99 :pep:`249` - Database API Specification 2.0
100 PEP written by Marc-André Lemburg.
101
102
103.. _sqlite3-module-contents:
104
105Module functions and constants
106------------------------------
107
108
109.. data:: PARSE_DECLTYPES
110
111 This constant is meant to be used with the *detect_types* parameter of the
112 :func:`connect` function.
113
114 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000115 column it returns. It will parse out the first word of the declared type,
116 i. e. for "integer primary key", it will parse out "integer", or for
117 "number(10)" it will parse out "number". Then for that column, it will look
118 into the converters dictionary and use the converter function registered for
119 that type there.
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121
122.. data:: PARSE_COLNAMES
123
124 This constant is meant to be used with the *detect_types* parameter of the
125 :func:`connect` function.
126
127 Setting this makes the SQLite interface parse the column name for each column it
128 returns. It will look for a string formed [mytype] in there, and then decide
129 that 'mytype' is the type of the column. It will try to find an entry of
130 'mytype' in the converters dictionary and then use the converter function found
131 there to return the value. The column name found in :attr:`cursor.description`
132 is only the first word of the column name, i. e. if you use something like
133 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
134 first blank for the column name: the column name would simply be "x".
135
136
137.. function:: connect(database[, timeout, isolation_level, detect_types, factory])
138
139 Opens a connection to the SQLite database file *database*. You can use
140 ``":memory:"`` to open a database connection to a database that resides in RAM
141 instead of on disk.
142
143 When a database is accessed by multiple connections, and one of the processes
144 modifies the database, the SQLite database is locked until that transaction is
145 committed. The *timeout* parameter specifies how long the connection should wait
146 for the lock to go away until raising an exception. The default for the timeout
147 parameter is 5.0 (five seconds).
148
149 For the *isolation_level* parameter, please see the
150 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
151
152 SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
153 you want to use other types you must add support for them yourself. The
154 *detect_types* parameter and the using custom **converters** registered with the
155 module-level :func:`register_converter` function allow you to easily do that.
156
157 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
158 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
159 type detection on.
160
161 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
162 connect call. You can, however, subclass the :class:`Connection` class and make
163 :func:`connect` use your class instead by providing your class for the *factory*
164 parameter.
165
166 Consult the section :ref:`sqlite3-types` of this manual for details.
167
168 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
169 overhead. If you want to explicitly set the number of statements that are cached
170 for the connection, you can set the *cached_statements* parameter. The currently
171 implemented default is to cache 100 statements.
172
173
174.. function:: register_converter(typename, callable)
175
176 Registers a callable to convert a bytestring from the database into a custom
177 Python type. The callable will be invoked for all database values that are of
178 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
179 function for how the type detection works. Note that the case of *typename* and
180 the name of the type in your query must match!
181
182
183.. function:: register_adapter(type, callable)
184
185 Registers a callable to convert the custom Python type *type* into one of
186 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000187 the Python value, and must return a value of the following types: int,
Georg Brandlf6945182008-02-01 11:56:49 +0000188 float, str, bytes (UTF-8 encoded) or buffer.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190
191.. function:: complete_statement(sql)
192
193 Returns :const:`True` if the string *sql* contains one or more complete SQL
194 statements terminated by semicolons. It does not verify that the SQL is
195 syntactically correct, only that there are no unclosed string literals and the
196 statement is terminated by a semicolon.
197
198 This can be used to build a shell for SQLite, as in the following example:
199
200
201 .. literalinclude:: ../includes/sqlite3/complete_statement.py
202
203
204.. function:: enable_callback_tracebacks(flag)
205
206 By default you will not get any tracebacks in user-defined functions,
207 aggregates, converters, authorizer callbacks etc. If you want to debug them, you
208 can call this function with *flag* as True. Afterwards, you will get tracebacks
209 from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
210 again.
211
212
213.. _sqlite3-connection-objects:
214
215Connection Objects
216------------------
217
218A :class:`Connection` instance has the following attributes and methods:
219
220.. attribute:: Connection.isolation_level
221
222 Get or set the current isolation level. None for autocommit mode or one of
223 "DEFERRED", "IMMEDIATE" or "EXLUSIVE". See section
224 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
225
226
227.. method:: Connection.cursor([cursorClass])
228
229 The cursor method accepts a single optional parameter *cursorClass*. If
230 supplied, this must be a custom cursor class that extends
231 :class:`sqlite3.Cursor`.
232
233
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000234.. method:: Connection.commit()
235
236 This method commits the current transaction. If you don't call this method,
237 anything you did since the last call to commit() is not visible from from
238 other database connections. If you wonder why you don't see the data you've
239 written to the database, please check you didn't forget to call this method.
240
241.. method:: Connection.rollback()
242
243 This method rolls back any changes to the database since the last call to
244 :meth:`commit`.
245
246.. method:: Connection.close()
247
248 This closes the database connection. Note that this does not automatically
249 call :meth:`commit`. If you just close your database connection without
250 calling :meth:`commit` first, your changes will be lost!
251
Georg Brandl116aa622007-08-15 14:28:22 +0000252.. method:: Connection.execute(sql, [parameters])
253
254 This is a nonstandard shortcut that creates an intermediate cursor object by
255 calling the cursor method, then calls the cursor's :meth:`execute` method with
256 the parameters given.
257
258
259.. method:: Connection.executemany(sql, [parameters])
260
261 This is a nonstandard shortcut that creates an intermediate cursor object by
262 calling the cursor method, then calls the cursor's :meth:`executemany` method
263 with the parameters given.
264
265
266.. method:: Connection.executescript(sql_script)
267
268 This is a nonstandard shortcut that creates an intermediate cursor object by
269 calling the cursor method, then calls the cursor's :meth:`executescript` method
270 with the parameters given.
271
272
273.. method:: Connection.create_function(name, num_params, func)
274
275 Creates a user-defined function that you can later use from within SQL
276 statements under the function name *name*. *num_params* is the number of
277 parameters the function accepts, and *func* is a Python callable that is called
278 as the SQL function.
279
Georg Brandlf6945182008-02-01 11:56:49 +0000280 The function can return any of the types supported by SQLite: bytes, str, int,
Georg Brandl5c106642007-11-29 17:41:05 +0000281 float, buffer and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283 Example:
284
285 .. literalinclude:: ../includes/sqlite3/md5func.py
286
287
288.. method:: Connection.create_aggregate(name, num_params, aggregate_class)
289
290 Creates a user-defined aggregate function.
291
292 The aggregate class must implement a ``step`` method, which accepts the number
293 of parameters *num_params*, and a ``finalize`` method which will return the
294 final result of the aggregate.
295
296 The ``finalize`` method can return any of the types supported by SQLite:
Georg Brandlf6945182008-02-01 11:56:49 +0000297 bytes, str, int, float, buffer and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299 Example:
300
301 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
302
303
304.. method:: Connection.create_collation(name, callable)
305
306 Creates a collation with the specified *name* and *callable*. The callable will
307 be passed two string arguments. It should return -1 if the first is ordered
308 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
309 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
310 your comparisons don't affect other SQL operations.
311
312 Note that the callable will get its parameters as Python bytestrings, which will
313 normally be encoded in UTF-8.
314
315 The following example shows a custom collation that sorts "the wrong way":
316
317 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
318
319 To remove a collation, call ``create_collation`` with None as callable::
320
321 con.create_collation("reverse", None)
322
323
324.. method:: Connection.interrupt()
325
326 You can call this method from a different thread to abort any queries that might
327 be executing on the connection. The query will then abort and the caller will
328 get an exception.
329
330
331.. method:: Connection.set_authorizer(authorizer_callback)
332
333 This routine registers a callback. The callback is invoked for each attempt to
334 access a column of a table in the database. The callback should return
335 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
336 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
337 column should be treated as a NULL value. These constants are available in the
338 :mod:`sqlite3` module.
339
340 The first argument to the callback signifies what kind of operation is to be
341 authorized. The second and third argument will be arguments or :const:`None`
342 depending on the first argument. The 4th argument is the name of the database
343 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
344 inner-most trigger or view that is responsible for the access attempt or
345 :const:`None` if this access attempt is directly from input SQL code.
346
347 Please consult the SQLite documentation about the possible values for the first
348 argument and the meaning of the second and third argument depending on the first
349 one. All necessary constants are available in the :mod:`sqlite3` module.
350
351
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000352.. method:: Connection.set_progress_handler(handler, n)
353
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000354 This routine registers a callback. The callback is invoked for every *n*
355 instructions of the SQLite virtual machine. This is useful if you want to
356 get called from SQLite during long-running operations, for example to update
357 a GUI.
358
359 If you want to clear any previously installed progress handler, call the
360 method with :const:`None` for *handler*.
361
362
Georg Brandl116aa622007-08-15 14:28:22 +0000363.. attribute:: Connection.row_factory
364
365 You can change this attribute to a callable that accepts the cursor and the
366 original row as a tuple and will return the real result row. This way, you can
367 implement more advanced ways of returning results, such as returning an object
368 that can also access columns by name.
369
370 Example:
371
372 .. literalinclude:: ../includes/sqlite3/row_factory.py
373
374 If returning a tuple doesn't suffice and you want name-based access to
375 columns, you should consider setting :attr:`row_factory` to the
376 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
377 index-based and case-insensitive name-based access to columns with almost no
378 memory overhead. It will probably be better than your own custom
379 dictionary-based approach or even a db_row based solution.
380
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000381 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383
384.. attribute:: Connection.text_factory
385
386 Using this attribute you can control what objects are returned for the TEXT data
Georg Brandlf6945182008-02-01 11:56:49 +0000387 type. By default, this attribute is set to :class:`str` and the
388 :mod:`sqlite3` module will return strings for TEXT. If you want to
389 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Georg Brandlf6945182008-02-01 11:56:49 +0000391 For efficiency reasons, there's also a way to return :class:`str` objects
392 only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
393 this attribute to :const:`sqlite3.OptimizedUnicode`.
Georg Brandl116aa622007-08-15 14:28:22 +0000394
395 You can also set it to any other callable that accepts a single bytestring
396 parameter and returns the resulting object.
397
398 See the following example code for illustration:
399
400 .. literalinclude:: ../includes/sqlite3/text_factory.py
401
402
403.. attribute:: Connection.total_changes
404
405 Returns the total number of database rows that have been modified, inserted, or
406 deleted since the database connection was opened.
407
408
Christian Heimesbbe741d2008-03-28 10:53:29 +0000409.. attribute:: Connection.iterdump
410
411 Returns an iterator to dump the database in an SQL text format. Useful when
412 saving an in-memory database for later restoration. This function provides
413 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
414 shell.
415
Christian Heimesbbe741d2008-03-28 10:53:29 +0000416 Example::
417
418 # Convert file existing_db.db to SQL dump file dump.sql
419 import sqlite3, os
420
421 con = sqlite3.connect('existing_db.db')
422 full_dump = os.linesep.join([line for line in con.iterdump()])
423 f = open('dump.sql', 'w')
424 f.writelines(full_dump)
425 f.close()
426
427
Georg Brandl116aa622007-08-15 14:28:22 +0000428.. _sqlite3-cursor-objects:
429
430Cursor Objects
431--------------
432
433A :class:`Cursor` instance has the following attributes and methods:
434
435
436.. method:: Cursor.execute(sql, [parameters])
437
Christian Heimesfdab48e2008-01-20 09:06:41 +0000438 Executes an SQL statement. The SQL statement may be parametrized (i. e.
Georg Brandl116aa622007-08-15 14:28:22 +0000439 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
440 kinds of placeholders: question marks (qmark style) and named placeholders
441 (named style).
442
443 This example shows how to use parameters with qmark style:
444
445 .. literalinclude:: ../includes/sqlite3/execute_1.py
446
447 This example shows how to use the named style:
448
449 .. literalinclude:: ../includes/sqlite3/execute_2.py
450
451 :meth:`execute` will only execute a single SQL statement. If you try to execute
452 more than one statement with it, it will raise a Warning. Use
453 :meth:`executescript` if you want to execute multiple SQL statements with one
454 call.
455
456
457.. method:: Cursor.executemany(sql, seq_of_parameters)
458
Christian Heimesfdab48e2008-01-20 09:06:41 +0000459 Executes an SQL command against all parameter sequences or mappings found in
Georg Brandl9afde1c2007-11-01 20:32:30 +0000460 the sequence *sql*. The :mod:`sqlite3` module also allows using an
461 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463 .. literalinclude:: ../includes/sqlite3/executemany_1.py
464
Georg Brandl9afde1c2007-11-01 20:32:30 +0000465 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000466
467 .. literalinclude:: ../includes/sqlite3/executemany_2.py
468
469
470.. method:: Cursor.executescript(sql_script)
471
472 This is a nonstandard convenience method for executing multiple SQL statements
473 at once. It issues a COMMIT statement first, then executes the SQL script it
474 gets as a parameter.
475
Georg Brandlf6945182008-02-01 11:56:49 +0000476 *sql_script* can be an instance of :class:`str` or :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000477
478 Example:
479
480 .. literalinclude:: ../includes/sqlite3/executescript.py
481
482
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000483.. method:: Cursor.fetchone()
484
Christian Heimesfdab48e2008-01-20 09:06:41 +0000485 Fetches the next row of a query result set, returning a single sequence,
486 or ``None`` when no more data is available.
487
488
489.. method:: Cursor.fetchmany([size=cursor.arraysize])
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000490
Christian Heimesfdab48e2008-01-20 09:06:41 +0000491 Fetches the next set of rows of a query result, returning a list. An empty
492 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000493
Christian Heimesfdab48e2008-01-20 09:06:41 +0000494 The number of rows to fetch per call is specified by the *size* parameter.
495 If it is not given, the cursor's arraysize determines the number of rows
496 to be fetched. The method should try to fetch as many rows as indicated by
497 the size parameter. If this is not possible due to the specified number of
498 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000499
Christian Heimesfdab48e2008-01-20 09:06:41 +0000500 Note there are performance considerations involved with the *size* parameter.
501 For optimal performance, it is usually best to use the arraysize attribute.
502 If the *size* parameter is used, then it is best for it to retain the same
503 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000504
505.. method:: Cursor.fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000506
507 Fetches all (remaining) rows of a query result, returning a list. Note that
508 the cursor's arraysize attribute can affect the performance of this operation.
509 An empty list is returned when no rows are available.
510
511
Georg Brandl116aa622007-08-15 14:28:22 +0000512.. attribute:: Cursor.rowcount
513
514 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
515 attribute, the database engine's own support for the determination of "rows
516 affected"/"rows selected" is quirky.
517
Georg Brandl116aa622007-08-15 14:28:22 +0000518 For ``DELETE`` statements, SQLite reports :attr:`rowcount` as 0 if you make a
519 ``DELETE FROM table`` without any condition.
520
521 For :meth:`executemany` statements, the number of modifications are summed up
522 into :attr:`rowcount`.
523
524 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
525 case no executeXX() has been performed on the cursor or the rowcount of the last
526 operation is not determinable by the interface".
527
Guido van Rossum04110fb2007-08-24 16:32:05 +0000528 This includes ``SELECT`` statements because we cannot determine the number of
529 rows a query produced until all rows were fetched.
530
Gerhard Häringd3372792008-03-29 19:13:55 +0000531.. attribute:: Cursor.lastrowid
532
533 This read-only attribute provides the rowid of the last modified row. It is
534 only set if you issued a ``INSERT`` statement using the :meth:`execute`
535 method. For operations other than ``INSERT`` or when :meth:`executemany` is
536 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl116aa622007-08-15 14:28:22 +0000537
538.. _sqlite3-types:
539
540SQLite and Python types
541-----------------------
542
543
544Introduction
545^^^^^^^^^^^^
546
547SQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB.
548
549The following Python types can thus be sent to SQLite without any problem:
550
Georg Brandlf6945182008-02-01 11:56:49 +0000551+-------------------------------+-------------+
552| Python type | SQLite type |
553+===============================+=============+
554| ``None`` | NULL |
555+-------------------------------+-------------+
556| :class:`int` | INTEGER |
557+-------------------------------+-------------+
558| :class:`float` | REAL |
559+-------------------------------+-------------+
560| :class:`bytes` (UTF8-encoded) | TEXT |
561+-------------------------------+-------------+
562| :class:`str` | TEXT |
563+-------------------------------+-------------+
564| :class:`buffer` | BLOB |
565+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000566
567This is how SQLite types are converted to Python types by default:
568
569+-------------+---------------------------------------------+
570| SQLite type | Python type |
571+=============+=============================================+
572| ``NULL`` | None |
573+-------------+---------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000574| ``INTEGER`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000575+-------------+---------------------------------------------+
576| ``REAL`` | float |
577+-------------+---------------------------------------------+
Georg Brandlf6945182008-02-01 11:56:49 +0000578| ``TEXT`` | depends on text_factory, str by default |
Georg Brandl116aa622007-08-15 14:28:22 +0000579+-------------+---------------------------------------------+
580| ``BLOB`` | buffer |
581+-------------+---------------------------------------------+
582
583The type system of the :mod:`sqlite3` module is extensible in two ways: you can
584store additional Python types in a SQLite database via object adaptation, and
585you can let the :mod:`sqlite3` module convert SQLite types to different Python
586types via converters.
587
588
589Using adapters to store additional Python types in SQLite databases
590^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
591
592As described before, SQLite supports only a limited set of types natively. To
593use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000594sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Georg Brandlf6945182008-02-01 11:56:49 +0000595str, bytes, buffer.
Georg Brandl116aa622007-08-15 14:28:22 +0000596
597The :mod:`sqlite3` module uses Python object adaptation, as described in
598:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
599
600There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
601type to one of the supported ones.
602
603
604Letting your object adapt itself
605""""""""""""""""""""""""""""""""
606
607This is a good approach if you write the class yourself. Let's suppose you have
608a class like this::
609
610 class Point(object):
611 def __init__(self, x, y):
612 self.x, self.y = x, y
613
614Now you want to store the point in a single SQLite column. First you'll have to
615choose one of the supported types first to be used for representing the point.
616Let's just use str and separate the coordinates using a semicolon. Then you need
617to give your class a method ``__conform__(self, protocol)`` which must return
618the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
619
620.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
621
622
623Registering an adapter callable
624"""""""""""""""""""""""""""""""
625
626The other possibility is to create a function that converts the type to the
627string representation and register the function with :meth:`register_adapter`.
628
Georg Brandl116aa622007-08-15 14:28:22 +0000629.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
630
631The :mod:`sqlite3` module has two default adapters for Python's built-in
632:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
633we want to store :class:`datetime.datetime` objects not in ISO representation,
634but as a Unix timestamp.
635
636.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
637
638
639Converting SQLite values to custom Python types
640^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
641
642Writing an adapter lets you send custom Python types to SQLite. But to make it
643really useful we need to make the Python to SQLite to Python roundtrip work.
644
645Enter converters.
646
647Let's go back to the :class:`Point` class. We stored the x and y coordinates
648separated via semicolons as strings in SQLite.
649
650First, we'll define a converter function that accepts the string as a parameter
651and constructs a :class:`Point` object from it.
652
653.. note::
654
655 Converter functions **always** get called with a string, no matter under which
656 data type you sent the value to SQLite.
657
Georg Brandl116aa622007-08-15 14:28:22 +0000658::
659
660 def convert_point(s):
661 x, y = map(float, s.split(";"))
662 return Point(x, y)
663
664Now you need to make the :mod:`sqlite3` module know that what you select from
665the database is actually a point. There are two ways of doing this:
666
667* Implicitly via the declared type
668
669* Explicitly via the column name
670
671Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
672for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
673
674The following example illustrates both approaches.
675
676.. literalinclude:: ../includes/sqlite3/converter_point.py
677
678
679Default adapters and converters
680^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
681
682There are default adapters for the date and datetime types in the datetime
683module. They will be sent as ISO dates/ISO timestamps to SQLite.
684
685The default converters are registered under the name "date" for
686:class:`datetime.date` and under the name "timestamp" for
687:class:`datetime.datetime`.
688
689This way, you can use date/timestamps from Python without any additional
690fiddling in most cases. The format of the adapters is also compatible with the
691experimental SQLite date/time functions.
692
693The following example demonstrates this.
694
695.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
696
697
698.. _sqlite3-controlling-transactions:
699
700Controlling Transactions
701------------------------
702
703By default, the :mod:`sqlite3` module opens transactions implicitly before a
704Data Modification Language (DML) statement (i.e. INSERT/UPDATE/DELETE/REPLACE),
705and commits transactions implicitly before a non-DML, non-query statement (i. e.
706anything other than SELECT/INSERT/UPDATE/DELETE/REPLACE).
707
708So if you are within a transaction and issue a command like ``CREATE TABLE
709...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
710before executing that command. There are two reasons for doing that. The first
711is that some of these commands don't work within transactions. The other reason
712is that pysqlite needs to keep track of the transaction state (if a transaction
713is active or not).
714
715You can control which kind of "BEGIN" statements pysqlite implicitly executes
716(or none at all) via the *isolation_level* parameter to the :func:`connect`
717call, or via the :attr:`isolation_level` property of connections.
718
719If you want **autocommit mode**, then set :attr:`isolation_level` to None.
720
721Otherwise leave it at its default, which will result in a plain "BEGIN"
722statement, or set it to one of SQLite's supported isolation levels: DEFERRED,
723IMMEDIATE or EXCLUSIVE.
724
Georg Brandl116aa622007-08-15 14:28:22 +0000725
726
727Using pysqlite efficiently
728--------------------------
729
730
731Using shortcut methods
732^^^^^^^^^^^^^^^^^^^^^^
733
734Using the nonstandard :meth:`execute`, :meth:`executemany` and
735:meth:`executescript` methods of the :class:`Connection` object, your code can
736be written more concisely because you don't have to create the (often
737superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
738objects are created implicitly and these shortcut methods return the cursor
739objects. This way, you can execute a SELECT statement and iterate over it
740directly using only a single call on the :class:`Connection` object.
741
742.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
743
744
745Accessing columns by name instead of by index
746^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
747
748One useful feature of the :mod:`sqlite3` module is the builtin
749:class:`sqlite3.Row` class designed to be used as a row factory.
750
751Rows wrapped with this class can be accessed both by index (like tuples) and
752case-insensitively by name:
753
754.. literalinclude:: ../includes/sqlite3/rowclass.py
755
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000756
757Using the connection as a context manager
758^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
759
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000760Connection objects can be used as context managers
761that automatically commit or rollback transactions. In the event of an
762exception, the transaction is rolled back; otherwise, the transaction is
763committed:
764
765.. literalinclude:: ../includes/sqlite3/ctx_manager.py