blob: 0b569bf3c16117a557feaa72a02342b68ed41f0b [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`sqlite3` --- DB-API 2.0 interface for SQLite databases
3============================================================
4
5.. module:: sqlite3
6 :synopsis: A DB-API 2.0 implementation using SQLite 3.x.
7.. sectionauthor:: Gerhard Häring <gh@ghaering.de>
8
9
Georg Brandl116aa622007-08-15 14:28:22 +000010SQLite is a C library that provides a lightweight disk-based database that
11doesn't require a separate server process and allows accessing the database
12using a nonstandard variant of the SQL query language. Some applications can use
13SQLite for internal data storage. It's also possible to prototype an
14application using SQLite and then port the code to a larger database such as
15PostgreSQL or Oracle.
16
17pysqlite was written by Gerhard Häring and provides a SQL interface compliant
18with the DB-API 2.0 specification described by :pep:`249`.
19
20To use the module, you must first create a :class:`Connection` object that
21represents the database. Here the data will be stored in the
22:file:`/tmp/example` file::
23
24 conn = sqlite3.connect('/tmp/example')
25
26You can also supply the special name ``:memory:`` to create a database in RAM.
27
28Once you have a :class:`Connection`, you can create a :class:`Cursor` object
29and call its :meth:`execute` method to perform SQL commands::
30
31 c = conn.cursor()
32
33 # Create table
34 c.execute('''create table stocks
35 (date text, trans text, symbol text,
36 qty real, price real)''')
37
38 # Insert a row of data
39 c.execute("""insert into stocks
40 values ('2006-01-05','BUY','RHAT',100,35.14)""")
41
42 # Save (commit) the changes
43 conn.commit()
44
45 # We can also close the cursor if we are done with it
46 c.close()
47
48Usually your SQL operations will need to use values from Python variables. You
49shouldn't assemble your query using Python's string operations because doing so
50is insecure; it makes your program vulnerable to an SQL injection attack.
51
52Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
53wherever you want to use a value, and then provide a tuple of values as the
54second argument to the cursor's :meth:`execute` method. (Other database modules
55may use a different placeholder, such as ``%s`` or ``:1``.) For example::
56
57 # Never do this -- insecure!
58 symbol = 'IBM'
59 c.execute("... where symbol = '%s'" % symbol)
60
61 # Do this instead
62 t = (symbol,)
63 c.execute('select * from stocks where symbol=?', t)
64
65 # Larger example
66 for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
67 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
68 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
69 ):
70 c.execute('insert into stocks values (?,?,?,?,?)', t)
71
Georg Brandl9afde1c2007-11-01 20:32:30 +000072To retrieve data after executing a SELECT statement, you can either treat the
73cursor as an :term:`iterator`, call the cursor's :meth:`fetchone` method to
74retrieve a single matching row, or call :meth:`fetchall` to get a list of the
75matching rows.
Georg Brandl116aa622007-08-15 14:28:22 +000076
77This example uses the iterator form::
78
79 >>> c = conn.cursor()
80 >>> c.execute('select * from stocks order by price')
81 >>> for row in c:
Georg Brandl6911e3c2007-09-04 07:15:32 +000082 ... print(row)
Georg Brandl116aa622007-08-15 14:28:22 +000083 ...
84 (u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
85 (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
86 (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
87 (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
88 >>>
89
90
91.. seealso::
92
93 http://www.pysqlite.org
94 The pysqlite web page.
95
96 http://www.sqlite.org
97 The SQLite web page; the documentation describes the syntax and the available
98 data types for the supported SQL dialect.
99
100 :pep:`249` - Database API Specification 2.0
101 PEP written by Marc-André Lemburg.
102
103
104.. _sqlite3-module-contents:
105
106Module functions and constants
107------------------------------
108
109
110.. data:: PARSE_DECLTYPES
111
112 This constant is meant to be used with the *detect_types* parameter of the
113 :func:`connect` function.
114
115 Setting it makes the :mod:`sqlite3` module parse the declared type for each
116 column it returns. It will parse out the first word of the declared type, i. e.
117 for "integer primary key", it will parse out "integer". Then for that column, it
118 will look into the converters dictionary and use the converter function
119 registered for that type there. Converter names are case-sensitive!
120
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 Brandl116aa622007-08-15 14:28:22 +0000188 float, str (UTF-8 encoded), unicode or buffer.
189
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
234.. method:: Connection.execute(sql, [parameters])
235
236 This is a nonstandard shortcut that creates an intermediate cursor object by
237 calling the cursor method, then calls the cursor's :meth:`execute` method with
238 the parameters given.
239
240
241.. method:: Connection.executemany(sql, [parameters])
242
243 This is a nonstandard shortcut that creates an intermediate cursor object by
244 calling the cursor method, then calls the cursor's :meth:`executemany` method
245 with the parameters given.
246
247
248.. method:: Connection.executescript(sql_script)
249
250 This is a nonstandard shortcut that creates an intermediate cursor object by
251 calling the cursor method, then calls the cursor's :meth:`executescript` method
252 with the parameters given.
253
254
255.. method:: Connection.create_function(name, num_params, func)
256
257 Creates a user-defined function that you can later use from within SQL
258 statements under the function name *name*. *num_params* is the number of
259 parameters the function accepts, and *func* is a Python callable that is called
260 as the SQL function.
261
262 The function can return any of the types supported by SQLite: unicode, str, int,
Georg Brandl5c106642007-11-29 17:41:05 +0000263 float, buffer and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265 Example:
266
267 .. literalinclude:: ../includes/sqlite3/md5func.py
268
269
270.. method:: Connection.create_aggregate(name, num_params, aggregate_class)
271
272 Creates a user-defined aggregate function.
273
274 The aggregate class must implement a ``step`` method, which accepts the number
275 of parameters *num_params*, and a ``finalize`` method which will return the
276 final result of the aggregate.
277
278 The ``finalize`` method can return any of the types supported by SQLite:
Georg Brandl5c106642007-11-29 17:41:05 +0000279 unicode, str, int, float, buffer and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281 Example:
282
283 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
284
285
286.. method:: Connection.create_collation(name, callable)
287
288 Creates a collation with the specified *name* and *callable*. The callable will
289 be passed two string arguments. It should return -1 if the first is ordered
290 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
291 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
292 your comparisons don't affect other SQL operations.
293
294 Note that the callable will get its parameters as Python bytestrings, which will
295 normally be encoded in UTF-8.
296
297 The following example shows a custom collation that sorts "the wrong way":
298
299 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
300
301 To remove a collation, call ``create_collation`` with None as callable::
302
303 con.create_collation("reverse", None)
304
305
306.. method:: Connection.interrupt()
307
308 You can call this method from a different thread to abort any queries that might
309 be executing on the connection. The query will then abort and the caller will
310 get an exception.
311
312
313.. method:: Connection.set_authorizer(authorizer_callback)
314
315 This routine registers a callback. The callback is invoked for each attempt to
316 access a column of a table in the database. The callback should return
317 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
318 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
319 column should be treated as a NULL value. These constants are available in the
320 :mod:`sqlite3` module.
321
322 The first argument to the callback signifies what kind of operation is to be
323 authorized. The second and third argument will be arguments or :const:`None`
324 depending on the first argument. The 4th argument is the name of the database
325 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
326 inner-most trigger or view that is responsible for the access attempt or
327 :const:`None` if this access attempt is directly from input SQL code.
328
329 Please consult the SQLite documentation about the possible values for the first
330 argument and the meaning of the second and third argument depending on the first
331 one. All necessary constants are available in the :mod:`sqlite3` module.
332
333
334.. attribute:: Connection.row_factory
335
336 You can change this attribute to a callable that accepts the cursor and the
337 original row as a tuple and will return the real result row. This way, you can
338 implement more advanced ways of returning results, such as returning an object
339 that can also access columns by name.
340
341 Example:
342
343 .. literalinclude:: ../includes/sqlite3/row_factory.py
344
345 If returning a tuple doesn't suffice and you want name-based access to
346 columns, you should consider setting :attr:`row_factory` to the
347 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
348 index-based and case-insensitive name-based access to columns with almost no
349 memory overhead. It will probably be better than your own custom
350 dictionary-based approach or even a db_row based solution.
351
352 .. % XXX what's a db_row-based solution?
353
354
355.. attribute:: Connection.text_factory
356
357 Using this attribute you can control what objects are returned for the TEXT data
358 type. By default, this attribute is set to :class:`unicode` and the
359 :mod:`sqlite3` module will return Unicode objects for TEXT. If you want to
360 return bytestrings instead, you can set it to :class:`str`.
361
362 For efficiency reasons, there's also a way to return Unicode objects only for
363 non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to
364 :const:`sqlite3.OptimizedUnicode`.
365
366 You can also set it to any other callable that accepts a single bytestring
367 parameter and returns the resulting object.
368
369 See the following example code for illustration:
370
371 .. literalinclude:: ../includes/sqlite3/text_factory.py
372
373
374.. attribute:: Connection.total_changes
375
376 Returns the total number of database rows that have been modified, inserted, or
377 deleted since the database connection was opened.
378
379
380.. _sqlite3-cursor-objects:
381
382Cursor Objects
383--------------
384
385A :class:`Cursor` instance has the following attributes and methods:
386
387
388.. method:: Cursor.execute(sql, [parameters])
389
390 Executes a SQL statement. The SQL statement may be parametrized (i. e.
391 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
392 kinds of placeholders: question marks (qmark style) and named placeholders
393 (named style).
394
395 This example shows how to use parameters with qmark style:
396
397 .. literalinclude:: ../includes/sqlite3/execute_1.py
398
399 This example shows how to use the named style:
400
401 .. literalinclude:: ../includes/sqlite3/execute_2.py
402
403 :meth:`execute` will only execute a single SQL statement. If you try to execute
404 more than one statement with it, it will raise a Warning. Use
405 :meth:`executescript` if you want to execute multiple SQL statements with one
406 call.
407
408
409.. method:: Cursor.executemany(sql, seq_of_parameters)
410
Georg Brandl9afde1c2007-11-01 20:32:30 +0000411 Executes a SQL command against all parameter sequences or mappings found in
412 the sequence *sql*. The :mod:`sqlite3` module also allows using an
413 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000414
415 .. literalinclude:: ../includes/sqlite3/executemany_1.py
416
Georg Brandl9afde1c2007-11-01 20:32:30 +0000417 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000418
419 .. literalinclude:: ../includes/sqlite3/executemany_2.py
420
421
422.. method:: Cursor.executescript(sql_script)
423
424 This is a nonstandard convenience method for executing multiple SQL statements
425 at once. It issues a COMMIT statement first, then executes the SQL script it
426 gets as a parameter.
427
428 *sql_script* can be a bytestring or a Unicode string.
429
430 Example:
431
432 .. literalinclude:: ../includes/sqlite3/executescript.py
433
434
435.. attribute:: Cursor.rowcount
436
437 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
438 attribute, the database engine's own support for the determination of "rows
439 affected"/"rows selected" is quirky.
440
Georg Brandl116aa622007-08-15 14:28:22 +0000441 For ``DELETE`` statements, SQLite reports :attr:`rowcount` as 0 if you make a
442 ``DELETE FROM table`` without any condition.
443
444 For :meth:`executemany` statements, the number of modifications are summed up
445 into :attr:`rowcount`.
446
447 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
448 case no executeXX() has been performed on the cursor or the rowcount of the last
449 operation is not determinable by the interface".
450
Guido van Rossum04110fb2007-08-24 16:32:05 +0000451 This includes ``SELECT`` statements because we cannot determine the number of
452 rows a query produced until all rows were fetched.
453
Georg Brandl116aa622007-08-15 14:28:22 +0000454
455.. _sqlite3-types:
456
457SQLite and Python types
458-----------------------
459
460
461Introduction
462^^^^^^^^^^^^
463
464SQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB.
465
466The following Python types can thus be sent to SQLite without any problem:
467
468+------------------------+-------------+
469| Python type | SQLite type |
470+========================+=============+
471| ``None`` | NULL |
472+------------------------+-------------+
473| ``int`` | INTEGER |
474+------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000475| ``float`` | REAL |
476+------------------------+-------------+
477| ``str (UTF8-encoded)`` | TEXT |
478+------------------------+-------------+
479| ``unicode`` | TEXT |
480+------------------------+-------------+
481| ``buffer`` | BLOB |
482+------------------------+-------------+
483
484This is how SQLite types are converted to Python types by default:
485
486+-------------+---------------------------------------------+
487| SQLite type | Python type |
488+=============+=============================================+
489| ``NULL`` | None |
490+-------------+---------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000491| ``INTEGER`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000492+-------------+---------------------------------------------+
493| ``REAL`` | float |
494+-------------+---------------------------------------------+
495| ``TEXT`` | depends on text_factory, unicode by default |
496+-------------+---------------------------------------------+
497| ``BLOB`` | buffer |
498+-------------+---------------------------------------------+
499
500The type system of the :mod:`sqlite3` module is extensible in two ways: you can
501store additional Python types in a SQLite database via object adaptation, and
502you can let the :mod:`sqlite3` module convert SQLite types to different Python
503types via converters.
504
505
506Using adapters to store additional Python types in SQLite databases
507^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
508
509As described before, SQLite supports only a limited set of types natively. To
510use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000511sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Georg Brandl116aa622007-08-15 14:28:22 +0000512str, unicode, buffer.
513
514The :mod:`sqlite3` module uses Python object adaptation, as described in
515:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
516
517There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
518type to one of the supported ones.
519
520
521Letting your object adapt itself
522""""""""""""""""""""""""""""""""
523
524This is a good approach if you write the class yourself. Let's suppose you have
525a class like this::
526
527 class Point(object):
528 def __init__(self, x, y):
529 self.x, self.y = x, y
530
531Now you want to store the point in a single SQLite column. First you'll have to
532choose one of the supported types first to be used for representing the point.
533Let's just use str and separate the coordinates using a semicolon. Then you need
534to give your class a method ``__conform__(self, protocol)`` which must return
535the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
536
537.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
538
539
540Registering an adapter callable
541"""""""""""""""""""""""""""""""
542
543The other possibility is to create a function that converts the type to the
544string representation and register the function with :meth:`register_adapter`.
545
Georg Brandl116aa622007-08-15 14:28:22 +0000546.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
547
548The :mod:`sqlite3` module has two default adapters for Python's built-in
549:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
550we want to store :class:`datetime.datetime` objects not in ISO representation,
551but as a Unix timestamp.
552
553.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
554
555
556Converting SQLite values to custom Python types
557^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
558
559Writing an adapter lets you send custom Python types to SQLite. But to make it
560really useful we need to make the Python to SQLite to Python roundtrip work.
561
562Enter converters.
563
564Let's go back to the :class:`Point` class. We stored the x and y coordinates
565separated via semicolons as strings in SQLite.
566
567First, we'll define a converter function that accepts the string as a parameter
568and constructs a :class:`Point` object from it.
569
570.. note::
571
572 Converter functions **always** get called with a string, no matter under which
573 data type you sent the value to SQLite.
574
575.. note::
576
577 Converter names are looked up in a case-sensitive manner.
578
579::
580
581 def convert_point(s):
582 x, y = map(float, s.split(";"))
583 return Point(x, y)
584
585Now you need to make the :mod:`sqlite3` module know that what you select from
586the database is actually a point. There are two ways of doing this:
587
588* Implicitly via the declared type
589
590* Explicitly via the column name
591
592Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
593for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
594
595The following example illustrates both approaches.
596
597.. literalinclude:: ../includes/sqlite3/converter_point.py
598
599
600Default adapters and converters
601^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
602
603There are default adapters for the date and datetime types in the datetime
604module. They will be sent as ISO dates/ISO timestamps to SQLite.
605
606The default converters are registered under the name "date" for
607:class:`datetime.date` and under the name "timestamp" for
608:class:`datetime.datetime`.
609
610This way, you can use date/timestamps from Python without any additional
611fiddling in most cases. The format of the adapters is also compatible with the
612experimental SQLite date/time functions.
613
614The following example demonstrates this.
615
616.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
617
618
619.. _sqlite3-controlling-transactions:
620
621Controlling Transactions
622------------------------
623
624By default, the :mod:`sqlite3` module opens transactions implicitly before a
625Data Modification Language (DML) statement (i.e. INSERT/UPDATE/DELETE/REPLACE),
626and commits transactions implicitly before a non-DML, non-query statement (i. e.
627anything other than SELECT/INSERT/UPDATE/DELETE/REPLACE).
628
629So if you are within a transaction and issue a command like ``CREATE TABLE
630...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
631before executing that command. There are two reasons for doing that. The first
632is that some of these commands don't work within transactions. The other reason
633is that pysqlite needs to keep track of the transaction state (if a transaction
634is active or not).
635
636You can control which kind of "BEGIN" statements pysqlite implicitly executes
637(or none at all) via the *isolation_level* parameter to the :func:`connect`
638call, or via the :attr:`isolation_level` property of connections.
639
640If you want **autocommit mode**, then set :attr:`isolation_level` to None.
641
642Otherwise leave it at its default, which will result in a plain "BEGIN"
643statement, or set it to one of SQLite's supported isolation levels: DEFERRED,
644IMMEDIATE or EXCLUSIVE.
645
646As the :mod:`sqlite3` module needs to keep track of the transaction state, you
647should not use ``OR ROLLBACK`` or ``ON CONFLICT ROLLBACK`` in your SQL. Instead,
648catch the :exc:`IntegrityError` and call the :meth:`rollback` method of the
649connection yourself.
650
651
652Using pysqlite efficiently
653--------------------------
654
655
656Using shortcut methods
657^^^^^^^^^^^^^^^^^^^^^^
658
659Using the nonstandard :meth:`execute`, :meth:`executemany` and
660:meth:`executescript` methods of the :class:`Connection` object, your code can
661be written more concisely because you don't have to create the (often
662superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
663objects are created implicitly and these shortcut methods return the cursor
664objects. This way, you can execute a SELECT statement and iterate over it
665directly using only a single call on the :class:`Connection` object.
666
667.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
668
669
670Accessing columns by name instead of by index
671^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
672
673One useful feature of the :mod:`sqlite3` module is the builtin
674:class:`sqlite3.Row` class designed to be used as a row factory.
675
676Rows wrapped with this class can be accessed both by index (like tuples) and
677case-insensitively by name:
678
679.. literalinclude:: ../includes/sqlite3/rowclass.py
680