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