blob: d9ce73ef080939f5052c9ea0a8c6c73ec8a4999f [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
115 column it returns. It will parse out the first word of the declared type, i. e.
116 for "integer primary key", it will parse out "integer". Then for that column, it
117 will look into the converters dictionary and use the converter function
118 registered for that type there. Converter names are case-sensitive!
119
120
121.. data:: PARSE_COLNAMES
122
123 This constant is meant to be used with the *detect_types* parameter of the
124 :func:`connect` function.
125
126 Setting this makes the SQLite interface parse the column name for each column it
127 returns. It will look for a string formed [mytype] in there, and then decide
128 that 'mytype' is the type of the column. It will try to find an entry of
129 'mytype' in the converters dictionary and then use the converter function found
130 there to return the value. The column name found in :attr:`cursor.description`
131 is only the first word of the column name, i. e. if you use something like
132 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
133 first blank for the column name: the column name would simply be "x".
134
135
136.. function:: connect(database[, timeout, isolation_level, detect_types, factory])
137
138 Opens a connection to the SQLite database file *database*. You can use
139 ``":memory:"`` to open a database connection to a database that resides in RAM
140 instead of on disk.
141
142 When a database is accessed by multiple connections, and one of the processes
143 modifies the database, the SQLite database is locked until that transaction is
144 committed. The *timeout* parameter specifies how long the connection should wait
145 for the lock to go away until raising an exception. The default for the timeout
146 parameter is 5.0 (five seconds).
147
148 For the *isolation_level* parameter, please see the
149 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
150
151 SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
152 you want to use other types you must add support for them yourself. The
153 *detect_types* parameter and the using custom **converters** registered with the
154 module-level :func:`register_converter` function allow you to easily do that.
155
156 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
157 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
158 type detection on.
159
160 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
161 connect call. You can, however, subclass the :class:`Connection` class and make
162 :func:`connect` use your class instead by providing your class for the *factory*
163 parameter.
164
165 Consult the section :ref:`sqlite3-types` of this manual for details.
166
167 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
168 overhead. If you want to explicitly set the number of statements that are cached
169 for the connection, you can set the *cached_statements* parameter. The currently
170 implemented default is to cache 100 statements.
171
172
173.. function:: register_converter(typename, callable)
174
175 Registers a callable to convert a bytestring from the database into a custom
176 Python type. The callable will be invoked for all database values that are of
177 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
178 function for how the type detection works. Note that the case of *typename* and
179 the name of the type in your query must match!
180
181
182.. function:: register_adapter(type, callable)
183
184 Registers a callable to convert the custom Python type *type* into one of
185 SQLite's supported types. The callable *callable* accepts as single parameter
Georg Brandl5c106642007-11-29 17:41:05 +0000186 the Python value, and must return a value of the following types: int,
Georg Brandlf6945182008-02-01 11:56:49 +0000187 float, str, bytes (UTF-8 encoded) or buffer.
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189
190.. function:: complete_statement(sql)
191
192 Returns :const:`True` if the string *sql* contains one or more complete SQL
193 statements terminated by semicolons. It does not verify that the SQL is
194 syntactically correct, only that there are no unclosed string literals and the
195 statement is terminated by a semicolon.
196
197 This can be used to build a shell for SQLite, as in the following example:
198
199
200 .. literalinclude:: ../includes/sqlite3/complete_statement.py
201
202
203.. function:: enable_callback_tracebacks(flag)
204
205 By default you will not get any tracebacks in user-defined functions,
206 aggregates, converters, authorizer callbacks etc. If you want to debug them, you
207 can call this function with *flag* as True. Afterwards, you will get tracebacks
208 from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
209 again.
210
211
212.. _sqlite3-connection-objects:
213
214Connection Objects
215------------------
216
217A :class:`Connection` instance has the following attributes and methods:
218
219.. attribute:: Connection.isolation_level
220
221 Get or set the current isolation level. None for autocommit mode or one of
222 "DEFERRED", "IMMEDIATE" or "EXLUSIVE". See section
223 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
224
225
226.. method:: Connection.cursor([cursorClass])
227
228 The cursor method accepts a single optional parameter *cursorClass*. If
229 supplied, this must be a custom cursor class that extends
230 :class:`sqlite3.Cursor`.
231
232
233.. method:: Connection.execute(sql, [parameters])
234
235 This is a nonstandard shortcut that creates an intermediate cursor object by
236 calling the cursor method, then calls the cursor's :meth:`execute` method with
237 the parameters given.
238
239
240.. method:: Connection.executemany(sql, [parameters])
241
242 This is a nonstandard shortcut that creates an intermediate cursor object by
243 calling the cursor method, then calls the cursor's :meth:`executemany` method
244 with the parameters given.
245
246
247.. method:: Connection.executescript(sql_script)
248
249 This is a nonstandard shortcut that creates an intermediate cursor object by
250 calling the cursor method, then calls the cursor's :meth:`executescript` method
251 with the parameters given.
252
253
254.. method:: Connection.create_function(name, num_params, func)
255
256 Creates a user-defined function that you can later use from within SQL
257 statements under the function name *name*. *num_params* is the number of
258 parameters the function accepts, and *func* is a Python callable that is called
259 as the SQL function.
260
Georg Brandlf6945182008-02-01 11:56:49 +0000261 The function can return any of the types supported by SQLite: bytes, str, int,
Georg Brandl5c106642007-11-29 17:41:05 +0000262 float, buffer and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264 Example:
265
266 .. literalinclude:: ../includes/sqlite3/md5func.py
267
268
269.. method:: Connection.create_aggregate(name, num_params, aggregate_class)
270
271 Creates a user-defined aggregate function.
272
273 The aggregate class must implement a ``step`` method, which accepts the number
274 of parameters *num_params*, and a ``finalize`` method which will return the
275 final result of the aggregate.
276
277 The ``finalize`` method can return any of the types supported by SQLite:
Georg Brandlf6945182008-02-01 11:56:49 +0000278 bytes, str, int, float, buffer and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280 Example:
281
282 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
283
284
285.. method:: Connection.create_collation(name, callable)
286
287 Creates a collation with the specified *name* and *callable*. The callable will
288 be passed two string arguments. It should return -1 if the first is ordered
289 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
290 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
291 your comparisons don't affect other SQL operations.
292
293 Note that the callable will get its parameters as Python bytestrings, which will
294 normally be encoded in UTF-8.
295
296 The following example shows a custom collation that sorts "the wrong way":
297
298 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
299
300 To remove a collation, call ``create_collation`` with None as callable::
301
302 con.create_collation("reverse", None)
303
304
305.. method:: Connection.interrupt()
306
307 You can call this method from a different thread to abort any queries that might
308 be executing on the connection. The query will then abort and the caller will
309 get an exception.
310
311
312.. method:: Connection.set_authorizer(authorizer_callback)
313
314 This routine registers a callback. The callback is invoked for each attempt to
315 access a column of a table in the database. The callback should return
316 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
317 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
318 column should be treated as a NULL value. These constants are available in the
319 :mod:`sqlite3` module.
320
321 The first argument to the callback signifies what kind of operation is to be
322 authorized. The second and third argument will be arguments or :const:`None`
323 depending on the first argument. The 4th argument is the name of the database
324 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
325 inner-most trigger or view that is responsible for the access attempt or
326 :const:`None` if this access attempt is directly from input SQL code.
327
328 Please consult the SQLite documentation about the possible values for the first
329 argument and the meaning of the second and third argument depending on the first
330 one. All necessary constants are available in the :mod:`sqlite3` module.
331
332
333.. attribute:: Connection.row_factory
334
335 You can change this attribute to a callable that accepts the cursor and the
336 original row as a tuple and will return the real result row. This way, you can
337 implement more advanced ways of returning results, such as returning an object
338 that can also access columns by name.
339
340 Example:
341
342 .. literalinclude:: ../includes/sqlite3/row_factory.py
343
344 If returning a tuple doesn't suffice and you want name-based access to
345 columns, you should consider setting :attr:`row_factory` to the
346 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
347 index-based and case-insensitive name-based access to columns with almost no
348 memory overhead. It will probably be better than your own custom
349 dictionary-based approach or even a db_row based solution.
350
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000351 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353
354.. attribute:: Connection.text_factory
355
356 Using this attribute you can control what objects are returned for the TEXT data
Georg Brandlf6945182008-02-01 11:56:49 +0000357 type. By default, this attribute is set to :class:`str` and the
358 :mod:`sqlite3` module will return strings for TEXT. If you want to
359 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Georg Brandlf6945182008-02-01 11:56:49 +0000361 For efficiency reasons, there's also a way to return :class:`str` objects
362 only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
363 this attribute to :const:`sqlite3.OptimizedUnicode`.
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365 You can also set it to any other callable that accepts a single bytestring
366 parameter and returns the resulting object.
367
368 See the following example code for illustration:
369
370 .. literalinclude:: ../includes/sqlite3/text_factory.py
371
372
373.. attribute:: Connection.total_changes
374
375 Returns the total number of database rows that have been modified, inserted, or
376 deleted since the database connection was opened.
377
378
Christian Heimesbbe741d2008-03-28 10:53:29 +0000379.. attribute:: Connection.iterdump
380
381 Returns an iterator to dump the database in an SQL text format. Useful when
382 saving an in-memory database for later restoration. This function provides
383 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
384 shell.
385
386 .. versionadded:: 2.6
387
388 Example::
389
390 # Convert file existing_db.db to SQL dump file dump.sql
391 import sqlite3, os
392
393 con = sqlite3.connect('existing_db.db')
394 full_dump = os.linesep.join([line for line in con.iterdump()])
395 f = open('dump.sql', 'w')
396 f.writelines(full_dump)
397 f.close()
398
399
Georg Brandl116aa622007-08-15 14:28:22 +0000400.. _sqlite3-cursor-objects:
401
402Cursor Objects
403--------------
404
405A :class:`Cursor` instance has the following attributes and methods:
406
407
408.. method:: Cursor.execute(sql, [parameters])
409
Christian Heimesfdab48e2008-01-20 09:06:41 +0000410 Executes an SQL statement. The SQL statement may be parametrized (i. e.
Georg Brandl116aa622007-08-15 14:28:22 +0000411 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
412 kinds of placeholders: question marks (qmark style) and named placeholders
413 (named style).
414
415 This example shows how to use parameters with qmark style:
416
417 .. literalinclude:: ../includes/sqlite3/execute_1.py
418
419 This example shows how to use the named style:
420
421 .. literalinclude:: ../includes/sqlite3/execute_2.py
422
423 :meth:`execute` will only execute a single SQL statement. If you try to execute
424 more than one statement with it, it will raise a Warning. Use
425 :meth:`executescript` if you want to execute multiple SQL statements with one
426 call.
427
428
429.. method:: Cursor.executemany(sql, seq_of_parameters)
430
Christian Heimesfdab48e2008-01-20 09:06:41 +0000431 Executes an SQL command against all parameter sequences or mappings found in
Georg Brandl9afde1c2007-11-01 20:32:30 +0000432 the sequence *sql*. The :mod:`sqlite3` module also allows using an
433 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000434
435 .. literalinclude:: ../includes/sqlite3/executemany_1.py
436
Georg Brandl9afde1c2007-11-01 20:32:30 +0000437 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439 .. literalinclude:: ../includes/sqlite3/executemany_2.py
440
441
442.. method:: Cursor.executescript(sql_script)
443
444 This is a nonstandard convenience method for executing multiple SQL statements
445 at once. It issues a COMMIT statement first, then executes the SQL script it
446 gets as a parameter.
447
Georg Brandlf6945182008-02-01 11:56:49 +0000448 *sql_script* can be an instance of :class:`str` or :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450 Example:
451
452 .. literalinclude:: ../includes/sqlite3/executescript.py
453
454
Christian Heimesfdab48e2008-01-20 09:06:41 +0000455.. method:: Cursor.fetchone()
456
457 Fetches the next row of a query result set, returning a single sequence,
458 or ``None`` when no more data is available.
459
460
461.. method:: Cursor.fetchmany([size=cursor.arraysize])
462
463 Fetches the next set of rows of a query result, returning a list. An empty
464 list is returned when no more rows are available.
465
466 The number of rows to fetch per call is specified by the *size* parameter.
467 If it is not given, the cursor's arraysize determines the number of rows
468 to be fetched. The method should try to fetch as many rows as indicated by
469 the size parameter. If this is not possible due to the specified number of
470 rows not being available, fewer rows may be returned.
471
472 Note there are performance considerations involved with the *size* parameter.
473 For optimal performance, it is usually best to use the arraysize attribute.
474 If the *size* parameter is used, then it is best for it to retain the same
475 value from one :meth:`fetchmany` call to the next.
476
477.. method:: Cursor.fetchall()
478
479 Fetches all (remaining) rows of a query result, returning a list. Note that
480 the cursor's arraysize attribute can affect the performance of this operation.
481 An empty list is returned when no rows are available.
482
483
Georg Brandl116aa622007-08-15 14:28:22 +0000484.. attribute:: Cursor.rowcount
485
486 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
487 attribute, the database engine's own support for the determination of "rows
488 affected"/"rows selected" is quirky.
489
Georg Brandl116aa622007-08-15 14:28:22 +0000490 For ``DELETE`` statements, SQLite reports :attr:`rowcount` as 0 if you make a
491 ``DELETE FROM table`` without any condition.
492
493 For :meth:`executemany` statements, the number of modifications are summed up
494 into :attr:`rowcount`.
495
496 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
497 case no executeXX() has been performed on the cursor or the rowcount of the last
498 operation is not determinable by the interface".
499
Guido van Rossum04110fb2007-08-24 16:32:05 +0000500 This includes ``SELECT`` statements because we cannot determine the number of
501 rows a query produced until all rows were fetched.
502
Georg Brandl116aa622007-08-15 14:28:22 +0000503
504.. _sqlite3-types:
505
506SQLite and Python types
507-----------------------
508
509
510Introduction
511^^^^^^^^^^^^
512
513SQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB.
514
515The following Python types can thus be sent to SQLite without any problem:
516
Georg Brandlf6945182008-02-01 11:56:49 +0000517+-------------------------------+-------------+
518| Python type | SQLite type |
519+===============================+=============+
520| ``None`` | NULL |
521+-------------------------------+-------------+
522| :class:`int` | INTEGER |
523+-------------------------------+-------------+
524| :class:`float` | REAL |
525+-------------------------------+-------------+
526| :class:`bytes` (UTF8-encoded) | TEXT |
527+-------------------------------+-------------+
528| :class:`str` | TEXT |
529+-------------------------------+-------------+
530| :class:`buffer` | BLOB |
531+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000532
533This is how SQLite types are converted to Python types by default:
534
535+-------------+---------------------------------------------+
536| SQLite type | Python type |
537+=============+=============================================+
538| ``NULL`` | None |
539+-------------+---------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000540| ``INTEGER`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000541+-------------+---------------------------------------------+
542| ``REAL`` | float |
543+-------------+---------------------------------------------+
Georg Brandlf6945182008-02-01 11:56:49 +0000544| ``TEXT`` | depends on text_factory, str by default |
Georg Brandl116aa622007-08-15 14:28:22 +0000545+-------------+---------------------------------------------+
546| ``BLOB`` | buffer |
547+-------------+---------------------------------------------+
548
549The type system of the :mod:`sqlite3` module is extensible in two ways: you can
550store additional Python types in a SQLite database via object adaptation, and
551you can let the :mod:`sqlite3` module convert SQLite types to different Python
552types via converters.
553
554
555Using adapters to store additional Python types in SQLite databases
556^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
557
558As described before, SQLite supports only a limited set of types natively. To
559use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000560sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Georg Brandlf6945182008-02-01 11:56:49 +0000561str, bytes, buffer.
Georg Brandl116aa622007-08-15 14:28:22 +0000562
563The :mod:`sqlite3` module uses Python object adaptation, as described in
564:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
565
566There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
567type to one of the supported ones.
568
569
570Letting your object adapt itself
571""""""""""""""""""""""""""""""""
572
573This is a good approach if you write the class yourself. Let's suppose you have
574a class like this::
575
576 class Point(object):
577 def __init__(self, x, y):
578 self.x, self.y = x, y
579
580Now you want to store the point in a single SQLite column. First you'll have to
581choose one of the supported types first to be used for representing the point.
582Let's just use str and separate the coordinates using a semicolon. Then you need
583to give your class a method ``__conform__(self, protocol)`` which must return
584the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
585
586.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
587
588
589Registering an adapter callable
590"""""""""""""""""""""""""""""""
591
592The other possibility is to create a function that converts the type to the
593string representation and register the function with :meth:`register_adapter`.
594
Georg Brandl116aa622007-08-15 14:28:22 +0000595.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
596
597The :mod:`sqlite3` module has two default adapters for Python's built-in
598:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
599we want to store :class:`datetime.datetime` objects not in ISO representation,
600but as a Unix timestamp.
601
602.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
603
604
605Converting SQLite values to custom Python types
606^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
607
608Writing an adapter lets you send custom Python types to SQLite. But to make it
609really useful we need to make the Python to SQLite to Python roundtrip work.
610
611Enter converters.
612
613Let's go back to the :class:`Point` class. We stored the x and y coordinates
614separated via semicolons as strings in SQLite.
615
616First, we'll define a converter function that accepts the string as a parameter
617and constructs a :class:`Point` object from it.
618
619.. note::
620
621 Converter functions **always** get called with a string, no matter under which
622 data type you sent the value to SQLite.
623
624.. note::
625
626 Converter names are looked up in a case-sensitive manner.
627
628::
629
630 def convert_point(s):
631 x, y = map(float, s.split(";"))
632 return Point(x, y)
633
634Now you need to make the :mod:`sqlite3` module know that what you select from
635the database is actually a point. There are two ways of doing this:
636
637* Implicitly via the declared type
638
639* Explicitly via the column name
640
641Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
642for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
643
644The following example illustrates both approaches.
645
646.. literalinclude:: ../includes/sqlite3/converter_point.py
647
648
649Default adapters and converters
650^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
651
652There are default adapters for the date and datetime types in the datetime
653module. They will be sent as ISO dates/ISO timestamps to SQLite.
654
655The default converters are registered under the name "date" for
656:class:`datetime.date` and under the name "timestamp" for
657:class:`datetime.datetime`.
658
659This way, you can use date/timestamps from Python without any additional
660fiddling in most cases. The format of the adapters is also compatible with the
661experimental SQLite date/time functions.
662
663The following example demonstrates this.
664
665.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
666
667
668.. _sqlite3-controlling-transactions:
669
670Controlling Transactions
671------------------------
672
673By default, the :mod:`sqlite3` module opens transactions implicitly before a
674Data Modification Language (DML) statement (i.e. INSERT/UPDATE/DELETE/REPLACE),
675and commits transactions implicitly before a non-DML, non-query statement (i. e.
676anything other than SELECT/INSERT/UPDATE/DELETE/REPLACE).
677
678So if you are within a transaction and issue a command like ``CREATE TABLE
679...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
680before executing that command. There are two reasons for doing that. The first
681is that some of these commands don't work within transactions. The other reason
682is that pysqlite needs to keep track of the transaction state (if a transaction
683is active or not).
684
685You can control which kind of "BEGIN" statements pysqlite implicitly executes
686(or none at all) via the *isolation_level* parameter to the :func:`connect`
687call, or via the :attr:`isolation_level` property of connections.
688
689If you want **autocommit mode**, then set :attr:`isolation_level` to None.
690
691Otherwise leave it at its default, which will result in a plain "BEGIN"
692statement, or set it to one of SQLite's supported isolation levels: DEFERRED,
693IMMEDIATE or EXCLUSIVE.
694
695As the :mod:`sqlite3` module needs to keep track of the transaction state, you
696should not use ``OR ROLLBACK`` or ``ON CONFLICT ROLLBACK`` in your SQL. Instead,
697catch the :exc:`IntegrityError` and call the :meth:`rollback` method of the
698connection yourself.
699
700
701Using pysqlite efficiently
702--------------------------
703
704
705Using shortcut methods
706^^^^^^^^^^^^^^^^^^^^^^
707
708Using the nonstandard :meth:`execute`, :meth:`executemany` and
709:meth:`executescript` methods of the :class:`Connection` object, your code can
710be written more concisely because you don't have to create the (often
711superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
712objects are created implicitly and these shortcut methods return the cursor
713objects. This way, you can execute a SELECT statement and iterate over it
714directly using only a single call on the :class:`Connection` object.
715
716.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
717
718
719Accessing columns by name instead of by index
720^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
721
722One useful feature of the :mod:`sqlite3` module is the builtin
723:class:`sqlite3.Row` class designed to be used as a row factory.
724
725Rows wrapped with this class can be accessed both by index (like tuples) and
726case-insensitively by name:
727
728.. literalinclude:: ../includes/sqlite3/rowclass.py
729