blob: 512ae8838591da53f8c00f695428c9f97136233f [file] [log] [blame]
Gerhard Häringeb2e1922006-04-29 23:12:41 +00001\section{\module{sqlite3} ---
2 DB-API 2.0 interface for SQLite databases}
3
4\declaremodule{builtin}{sqlite3}
Fred Drake6550f032006-05-01 06:25:58 +00005\modulesynopsis{A DB-API 2.0 implementation using SQLite 3.x.}
Gerhard Häring2b161d92006-05-12 23:49:49 +00006\sectionauthor{Gerhard Häring}{gh@ghaering.de}
7\versionadded{2.5}
Gerhard Häringeb2e1922006-04-29 23:12:41 +00008
Andrew M. Kuchling12238d72006-06-07 13:55:33 +00009SQLite is a C library that provides a SQL-language database that
10stores data in disk files without requiring a separate server process.
11pysqlite was written by Gerhard H\"aring and provides a SQL interface
12compliant with the DB-API 2.0 specification described by
13\pep{249}. This means that it should be possible to write the first
14version of your applications using SQLite for data storage. If
15switching to a larger database such as PostgreSQL or Oracle is
16later necessary, the switch should be relatively easy.
17
18To use the module, you must first create a \class{Connection} object
19that represents the database. Here the data will be stored in the
20\file{/tmp/example} file:
21
22\begin{verbatim}
23conn = sqlite3.connect('/tmp/example')
24\end{verbatim}
25
26You can also supply the special name \samp{:memory:} to create
27a database in RAM.
28
29Once you have a \class{Connection}, you can create a \class{Cursor}
30object and call its \method{execute()} method to perform SQL commands:
31
32\begin{verbatim}
33c = conn.cursor()
34
35# Create table
36c.execute('''create table stocks
37(date timestamp, trans varchar, symbol varchar,
38 qty decimal, price decimal)''')
39
40# Insert a row of data
41c.execute("""insert into stocks
42 values ('2006-01-05','BUY','RHAT',100,35.14)""")
43\end{verbatim}
44
45Usually your SQL operations will need to use values from Python
46variables. You shouldn't assemble your query using Python's string
47operations because doing so is insecure; it makes your program
48vulnerable to an SQL injection attack.
49
50Instead, use SQLite's parameter substitution. Put \samp{?} as a
51placeholder wherever you want to use a value, and then provide a tuple
52of values as the second argument to the cursor's \method{execute()}
53method. For example:
54
55\begin{verbatim}
56# Never do this -- insecure!
57symbol = 'IBM'
58c.execute("... where symbol = '%s'" % symbol)
59
60# Do this instead
61t = (symbol,)
62c.execute('select * from stocks where symbol=?', t)
63
64# Larger example
65for 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\end{verbatim}
71
72To retrieve data after executing a SELECT statement, you can either
73treat the cursor as an iterator, call the cursor's \method{fetchone()}
74method to retrieve a single matching row,
75or call \method{fetchall()} to get a list of the matching rows.
76
77This example uses the iterator form:
78
79\begin{verbatim}
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\end{verbatim}
91
92\begin{seealso}
93
94\seeurl{http://www.pysqlite.org}
95{The pysqlite web page.}
96
97\seeurl{http://www.sqlite.org}
98{The SQLite web page; the documentation describes the syntax and the
99available data types for the supported SQL dialect.}
100
101\seepep{249}{Database API Specification 2.0}{PEP written by
102Marc-Andr\'e Lemburg.}
103
104\end{seealso}
105
106
Gerhard Häring2b161d92006-05-12 23:49:49 +0000107\subsection{Module functions and constants\label{sqlite3-Module-Contents}}
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000108
109\begin{datadesc}{PARSE_DECLTYPES}
Gerhard Häring2b161d92006-05-12 23:49:49 +0000110This constant is meant to be used with the \var{detect_types} parameter of the
111\function{connect} function.
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000112
Gerhard Häring2b161d92006-05-12 23:49:49 +0000113Setting it makes the \module{sqlite3} module parse the declared type for each column it
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000114returns. It will parse out the first word of the declared type, i. e. for
115"integer primary key", it will parse out "integer". Then for that column, it
Gerhard Häring2b161d92006-05-12 23:49:49 +0000116will look into the converters dictionary and use the converter function
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000117registered for that type there. Converter names are case-sensitive!
118\end{datadesc}
119
120
121\begin{datadesc}{PARSE_COLNAMES}
Gerhard Häring2b161d92006-05-12 23:49:49 +0000122This constant is meant to be used with the \var{detect_types} parameter of the
123\function{connect} function.
124
125Setting this makes the SQLite interface parse the column name for each column
126it returns. It will look for a string formed [mytype] in there, and then
127decide that 'mytype' is the type of the column. It will try to find an entry of
128'mytype' in the converters dictionary and then use the converter function found
129there to return the value. The column name found in \member{cursor.description} is only
130the first word of the column name, i. e. if you use something like
131\code{'as "x [datetime]"'} in your SQL, then we will parse out everything until the
132first blank for the column name: the column name would simply be "x".
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000133\end{datadesc}
134
Gerhard Häring2b161d92006-05-12 23:49:49 +0000135\begin{funcdesc}{connect}{database\optional{, timeout, isolation_level, detect_types, factory}}
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000136Opens a connection to the SQLite database file \var{database}. You can use
137\code{":memory:"} to open a database connection to a database that resides in
138RAM instead of on disk.
139
140When a database is accessed by multiple connections, and one of the processes
141modifies the database, the SQLite database is locked until that transaction is
142committed. The \var{timeout} parameter specifies how long the connection should
143wait for the lock to go away until raising an exception. The default for the
144timeout parameter is 5.0 (five seconds).
145
Gerhard Häring2b161d92006-05-12 23:49:49 +0000146For the \var{isolation_level} parameter, please see \member{isolation_level}
147\ref{sqlite3-Connection-IsolationLevel} property of \class{Connection} objects.
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000148
149SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
150you want to use other types, like you have to add support for them yourself.
Gerhard Häring2b161d92006-05-12 23:49:49 +0000151The \var{detect_types} parameter and the using custom \strong{converters} registered with
152the module-level \function{register_converter} function allow you to easily do that.
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000153
154\var{detect_types} defaults to 0 (i. e. off, no type detection), you can set it
Gerhard Häring2b161d92006-05-12 23:49:49 +0000155to any combination of \constant{PARSE_DECLTYPES} and \constant{PARSE_COLNAMES} to turn type
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000156detection on.
157
Gerhard Häring2b161d92006-05-12 23:49:49 +0000158By default, the \module{sqlite3} module uses its \class{Connection} class for the
159connect call. You can, however, subclass the \class{Connection} class and make
160\function{connect} use your class instead by providing your class for the
161\var{factory} parameter.
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000162
Gerhard Häring2b161d92006-05-12 23:49:49 +0000163Consult the section \ref{sqlite3-Types} of this manual for details.
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000164
Gerhard Häring2b161d92006-05-12 23:49:49 +0000165The \module{sqlite3} module internally uses a statement cache to avoid SQL parsing
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000166overhead. If you want to explicitly set the number of statements that are
167cached for the connection, you can set the \var{cached_statements} parameter.
168The currently implemented default is to cache 100 statements.
169\end{funcdesc}
170
171\begin{funcdesc}{register_converter}{typename, callable}
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000172Registers a callable to convert a bytestring from the database into a custom
173Python type. The callable will be invoked for all database values that are of
Gerhard Häring2b161d92006-05-12 23:49:49 +0000174the type \var{typename}. Confer the parameter \var{detect_types} of the
175\function{connect} function for how the type detection works. Note that the case of
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000176\var{typename} and the name of the type in your query must match!
177\end{funcdesc}
178
179\begin{funcdesc}{register_adapter}{type, callable}
180Registers a callable to convert the custom Python type \var{type} into one of
181SQLite's supported types. The callable \var{callable} accepts as single
182parameter the Python value, and must return a value of the following types:
183int, long, float, str (UTF-8 encoded), unicode or buffer.
184\end{funcdesc}
185
Gerhard Häring2b161d92006-05-12 23:49:49 +0000186\begin{funcdesc}{complete_statement}{sql}
187Returns \constant{True} if the string \var{sql} one or more complete SQL
188statements terminated by semicolons. It does not verify if the SQL is
189syntactically correct, only if there are no unclosed string literals and if the
190statement is terminated by a semicolon.
191
192This can be used to build a shell for SQLite, like in the following example:
193
194 \verbatiminput{sqlite3/complete_statement.py}
195\end{funcdesc}
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000196
Fred Drake6550f032006-05-01 06:25:58 +0000197\subsection{Connection Objects \label{sqlite3-Connection-Objects}}
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000198
199A \class{Connection} instance has the following attributes and methods:
200
Gerhard Häring2b161d92006-05-12 23:49:49 +0000201\label{sqlite3-Connection-IsolationLevel}
Fred Drake6550f032006-05-01 06:25:58 +0000202\begin{memberdesc}{isolation_level}
Gerhard Häring2b161d92006-05-12 23:49:49 +0000203 Get or set the current isolation level. None for autocommit mode or one of
204 "DEFERRED", "IMMEDIATE" or "EXLUSIVE". See Controlling Transactions
205 \ref{sqlite3-Controlling-Transactions} for a more detailed explanation.
Fred Drake6550f032006-05-01 06:25:58 +0000206\end{memberdesc}
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000207
208\begin{methoddesc}{cursor}{\optional{cursorClass}}
Fred Drake6550f032006-05-01 06:25:58 +0000209 The cursor method accepts a single optional parameter \var{cursorClass}.
210 This is a custom cursor class which must extend \class{sqlite3.Cursor}.
Gerhard Häringeb2e1922006-04-29 23:12:41 +0000211\end{methoddesc}
212
Gerhard Häring82560eb2006-05-01 15:14:48 +0000213\begin{methoddesc}{execute}{sql, \optional{parameters}}
214This is a nonstandard shortcut that creates an intermediate cursor object by
Gerhard Häring2b161d92006-05-12 23:49:49 +0000215calling the cursor method, then calls the cursor's \method{execute} method with the
Gerhard Häring82560eb2006-05-01 15:14:48 +0000216parameters given.
217\end{methoddesc}
218
219\begin{methoddesc}{executemany}{sql, \optional{parameters}}
220This is a nonstandard shortcut that creates an intermediate cursor object by
Gerhard Häring2b161d92006-05-12 23:49:49 +0000221calling the cursor method, then calls the cursor's \method{executemany} method with the
Gerhard Häring82560eb2006-05-01 15:14:48 +0000222parameters given.
223\end{methoddesc}
224
225\begin{methoddesc}{executescript}{sql_script}
226This is a nonstandard shortcut that creates an intermediate cursor object by
Gerhard Häring2b161d92006-05-12 23:49:49 +0000227calling the cursor method, then calls the cursor's \method{executescript} method with the
Gerhard Häring82560eb2006-05-01 15:14:48 +0000228parameters given.
229\end{methoddesc}
230
Gerhard Häring2b161d92006-05-12 23:49:49 +0000231\begin{methoddesc}{create_function}{name, num_params, func}
232
233Creates a user-defined function that you can later use from within SQL
234statements under the function name \var{name}. \var{num_params} is the number
235of parameters the function accepts, and \var{func} is a Python callable that is
236called as SQL function.
237
238The function can return any of the types supported by SQLite: unicode, str,
239int, long, float, buffer and None. Exceptions in the function are ignored and
240they are handled as if the function returned None.
241
242Example:
243
244 \verbatiminput{sqlite3/md5func.py}
245\end{methoddesc}
246
247\begin{methoddesc}{create_aggregate}{name, num_params, aggregate_class}
248
249Creates a user-defined aggregate function.
250
251The aggregate class must implement a \code{step} method, which accepts the
252number of parameters \var{num_params}, and a \code{finalize} method which
253will return the final result of the aggregate.
254
255The \code{finalize} method can return any of the types supported by SQLite:
256unicode, str, int, long, float, buffer and None. Any exceptions are ignored.
257
258Example:
259
260 \verbatiminput{sqlite3/mysumaggr.py}
261\end{methoddesc}
262
263\begin{methoddesc}{create_collation}{name, callable}
264
265Creates a collation with the specified \var{name} and \var{callable}. The
266callable will be passed two string arguments. It should return -1 if the first
267is ordered lower than the second, 0 if they are ordered equal and 1 and if the
268first is ordered higher than the second. Note that this controls sorting
269(ORDER BY in SQL) so your comparisons don't affect other SQL operations.
270
271Note that the callable will get its parameters as Python bytestrings, which
272will normally be encoded in UTF-8.
273
274The following example shows a custom collation that sorts "the wrong way":
275
276 \verbatiminput{sqlite3/collation_reverse.py}
277
278To remove a collation, call \code{create_collation} with None as callable:
279
280\begin{verbatim}
281 con.create_collation("reverse", None)
282\end{verbatim}
283\end{methoddesc}
284
285
Gerhard Häring82560eb2006-05-01 15:14:48 +0000286\begin{memberdesc}{row_factory}
287 You can change this attribute to a callable that accepts the cursor and
288 the original row as tuple and will return the real result row. This
289 way, you can implement more advanced ways of returning results, like
290 ones that can also access columns by name.
291
292 Example:
293
294 \verbatiminput{sqlite3/row_factory.py}
295
296 If the standard tuple types don't suffice for you, and you want name-based
297 access to columns, you should consider setting \member{row_factory} to the
Gerhard Häring2b161d92006-05-12 23:49:49 +0000298 highly-optimized sqlite3.Row type. It provides both
Gerhard Häring82560eb2006-05-01 15:14:48 +0000299 index-based and case-insensitive name-based access to columns with almost
300 no memory overhead. Much better than your own custom dictionary-based
301 approach or even a db_row based solution.
302\end{memberdesc}
303
304\begin{memberdesc}{text_factory}
Gerhard Häring2b161d92006-05-12 23:49:49 +0000305 Using this attribute you can control what objects are returned for the
306 TEXT data type. By default, this attribute is set to \class{unicode} and
307 the \module{sqlite3} module will return Unicode objects for TEXT. If you want to return
308 bytestrings instead, you can set it to \class{str}.
Gerhard Häring82560eb2006-05-01 15:14:48 +0000309
310 For efficiency reasons, there's also a way to return Unicode objects only
311 for non-ASCII data, and bytestrings otherwise. To activate it, set this
Gerhard Häring2b161d92006-05-12 23:49:49 +0000312 attribute to \constant{sqlite3.OptimizedUnicode}.
Gerhard Häring82560eb2006-05-01 15:14:48 +0000313
314 You can also set it to any other callable that accepts a single bytestring
315 parameter and returns the result object.
316
317 See the following example code for illustration:
318
319 \verbatiminput{sqlite3/text_factory.py}
320\end{memberdesc}
321
322\begin{memberdesc}{total_changes}
323 Returns the total number of database rows that have be modified, inserted,
324 or deleted since the database connection was opened.
325\end{memberdesc}
326
327
328
329
330
Gerhard Häring2b161d92006-05-12 23:49:49 +0000331\subsection{Cursor Objects \label{sqlite3-Cursor-Objects}}
Gerhard Häring82560eb2006-05-01 15:14:48 +0000332
333A \class{Cursor} instance has the following attributes and methods:
334
335\begin{methoddesc}{execute}{sql, \optional{parameters}}
336
337Executes a SQL statement. The SQL statement may be parametrized (i. e.
Gerhard Häring2b161d92006-05-12 23:49:49 +0000338placeholders instead of SQL literals). The \module{sqlite3} module supports two kinds of
Gerhard Häring82560eb2006-05-01 15:14:48 +0000339placeholders: question marks (qmark style) and named placeholders (named
340style).
341
342This example shows how to use parameters with qmark style:
343
344 \verbatiminput{sqlite3/execute_1.py}
345
346This example shows how to use the named style:
347
348 \verbatiminput{sqlite3/execute_2.py}
349
350 \method{execute} will only execute a single SQL statement. If you try to
351 execute more than one statement with it, it will raise a Warning. Use
352 \method{executescript} if want to execute multiple SQL statements with one
353 call.
354\end{methoddesc}
355
356
357\begin{methoddesc}{executemany}{sql, seq_of_parameters}
358Executes a SQL command against all parameter sequences or mappings found in the
359sequence \var{sql}. The \module{sqlite3} module also allows
360to use an iterator yielding parameters instead of a sequence.
361
362\verbatiminput{sqlite3/executemany_1.py}
363
364Here's a shorter example using a generator:
365
366\verbatiminput{sqlite3/executemany_2.py}
367\end{methoddesc}
368
369\begin{methoddesc}{executescript}{sql_script}
370
371This is a nonstandard convenience method for executing multiple SQL statements
372at once. It issues a COMMIT statement before, then executes the SQL script it
373gets as a parameter.
374
375\var{sql_script} can be a bytestring or a Unicode string.
376
377Example:
378
379\verbatiminput{sqlite3/executescript.py}
380\end{methoddesc}
381
382\begin{memberdesc}{rowcount}
Gerhard Häring2b161d92006-05-12 23:49:49 +0000383 Although the \class{Cursor} class of the \module{sqlite3} module implements this
Gerhard Häring82560eb2006-05-01 15:14:48 +0000384 attribute, the database engine's own support for the determination of "rows
385 affected"/"rows selected" is quirky.
386
387 For \code{SELECT} statements, \member{rowcount} is always None because we cannot
388 determine the number of rows a query produced until all rows were fetched.
389
390 For \code{DELETE} statements, SQLite reports \member{rowcount} as 0 if you make a
391 \code{DELETE FROM table} without any condition.
392
Gerhard Häring2b161d92006-05-12 23:49:49 +0000393 For \method{executemany} statements, the number of modifications are summed
394 up into \member{rowcount}.
Gerhard Häring82560eb2006-05-01 15:14:48 +0000395
396 As required by the Python DB API Spec, the \member{rowcount} attribute "is -1
397 in case no executeXX() has been performed on the cursor or the rowcount
398 of the last operation is not determinable by the interface".
399\end{memberdesc}
400
Gerhard Häring2b161d92006-05-12 23:49:49 +0000401\subsection{SQLite and Python types\label{sqlite3-Types}}
402
403\subsubsection{Introduction}
404
405SQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB.
406
407The following Python types can thus be sent to SQLite without any problem:
408
409\begin{tableii} {c|l}{code}{Python type}{SQLite type}
410\lineii{None}{NULL}
411\lineii{int}{INTEGER}
412\lineii{long}{INTEGER}
413\lineii{float}{REAL}
414\lineii{str (UTF8-encoded)}{TEXT}
415\lineii{unicode}{TEXT}
416\lineii{buffer}{BLOB}
417\end{tableii}
418
419This is how SQLite types are converted to Python types by default:
420
421\begin{tableii} {c|l}{code}{SQLite type}{Python type}
422\lineii{NULL}{None}
423\lineii{INTEGER}{int or long, depending on size}
424\lineii{REAL}{float}
425\lineii{TEXT}{depends on text_factory, unicode by default}
426\lineii{BLOB}{buffer}
427\end{tableii}
428
429The type system of the \module{sqlite3} module is extensible in both ways: you can store
430additional Python types in a SQLite database via object adaptation, and you can
431let the \module{sqlite3} module convert SQLite types to different Python types via
432converters.
433
434\subsubsection{Using adapters to store additional Python types in SQLite databases}
435
436Like described before, SQLite supports only a limited set of types natively. To
437use other Python types with SQLite, you must \strong{adapt} them to one of the sqlite3
438module's supported types for SQLite. So, one of NoneType, int, long, float,
439str, unicode, buffer.
440
441The \module{sqlite3} module uses the Python object adaptation, like described in PEP 246
442for this. The protocol to use is \class{PrepareProtocol}.
443
444There are two ways to enable the \module{sqlite3} module to adapt a custom Python type
445to one of the supported ones.
446
447\paragraph{Letting your object adapt itself}
448
449This is a good approach if you write the class yourself. Let's suppose you have
450a class like this:
451
452\begin{verbatim}
453class Point(object):
454 def __init__(self, x, y):
455 self.x, self.y = x, y
456\end{verbatim}
457
458Now you want to store the point in a single SQLite column. You'll have to
459choose one of the supported types first that you use to represent the point in.
460Let's just use str and separate the coordinates using a semicolon. Then you
461need to give your class a method \code{__conform__(self, protocol)} which must
462return the converted value. The parameter \var{protocol} will be
463\class{PrepareProtocol}.
464
465\verbatiminput{sqlite3/adapter_point_1.py}
466
467\paragraph{Registering an adapter callable}
468
469The other possibility is to create a function that converts the type to the
470string representation and register the function with \method{register_adapter}.
471
472 \verbatiminput{sqlite3/adapter_point_2.py}
473
474\begin{notice}
475The type/class to adapt must be a new-style class, i. e. it must have
476\class{object} as one of its bases.
477\end{notice}
478
479The \module{sqlite3} module has two default adapters for Python's builtin
480\class{datetime.date} and \class{datetime.datetime} types. Now let's suppose we
481want to store \class{datetime.datetime} objects not in ISO representation, but
482as Unix timestamp.
483
484 \verbatiminput{sqlite3/adapter_datetime.py}
485
486\subsubsection{Converting SQLite values to custom Python types}
487
488Now that's all nice and dandy that you can send custom Python types to SQLite.
489But to make it really useful we need to make the Python to SQLite to Python
490roundtrip work.
491
492Enter converters.
493
494Let's go back to the Point class. We stored the x and y coordinates separated
495via semicolons as strings in SQLite.
496
497Let's first define a converter function that accepts the string as a parameter and constructs a Point object from it.
498
499\begin{notice}
500Converter functions \strong{always} get called with a string, no matter
501under which data type you sent the value to SQLite.
502\end{notice}
503
504\begin{notice}
505Converter names are looked up in a case-sensitive manner.
506\end{notice}
507
508
509\begin{verbatim}
510 def convert_point(s):
511 x, y = map(float, s.split(";"))
512 return Point(x, y)
513\end{verbatim}
514
515Now you need to make the \module{sqlite3} module know that what you select from the
516database is actually a point. There are two ways of doing this:
517
518\begin{itemize}
519 \item Implicitly via the declared type
520 \item Explicitly via the column name
521\end{itemize}
522
523Both ways are described at \ref{sqlite3-Module-Contents} in the text explaining
524the constants \constant{PARSE_DECLTYPES} and \constant{PARSE_COlNAMES}.
525
526
527The following example illustrates both ways.
528
529 \verbatiminput{sqlite3/converter_point.py}
530
531\subsubsection{Default adapters and converters}
532
533There are default adapters for the date and datetime types in the datetime
534module. They will be sent as ISO dates/ISO timestamps to SQLite.
535
536The default converters are registered under the name "date" for datetime.date
537and under the name "timestamp" for datetime.datetime.
538
539This way, you can use date/timestamps from Python without any additional
540fiddling in most cases. The format of the adapters is also compatible with the
541experimental SQLite date/time functions.
542
543The following example demonstrates this.
544
545 \verbatiminput{sqlite3/pysqlite_datetime.py}
546
547\subsection{Controlling Transactions \label{sqlite3-Controlling-Transactions}}
548
549By default, the \module{sqlite3} module opens transactions implicitly before a DML
550statement (INSERT/UPDATE/DELETE/REPLACE), and commits transactions implicitly
551before a non-DML, non-DQL statement (i. e. anything other than
552SELECT/INSERT/UPDATE/DELETE/REPLACE).
553
554So if you are within a transaction, and issue a command like \code{CREATE TABLE
555...}, \code{VACUUM}, \code{PRAGMA}, the \module{sqlite3} module will commit implicitly
556before executing that command. There are two reasons for doing that. The first
557is that some of these commands don't work within transactions. The other reason
558is that pysqlite needs to keep track of the transaction state (if a transaction
559is active or not).
560
561You can control which kind of "BEGIN" statements pysqlite implicitly executes
562(or none at all) via the \var{isolation_level} parameter to the
563\function{connect} call, or via the \member{isolation_level} property of
564connections.
565
566If you want \strong{autocommit mode}, then set \member{isolation_level} to None.
567
568Otherwise leave it at it's default, which will result in a plain "BEGIN"
569statement, or set it to one of SQLite's supported isolation levels: DEFERRED,
570IMMEDIATE or EXCLUSIVE.
571
572As the \module{sqlite3} module needs to keep track of the transaction state, you should
573not use \code{OR ROLLBACK} or \code{ON CONFLICT ROLLBACK} in your SQL. Instead,
574catch the \exception{IntegrityError} and call the \method{rollback} method of
575the connection yourself.
576
577\subsection{Using pysqlite efficiently}
578
579\subsubsection{Using shortcut methods}
580
581Using the nonstandard \method{execute}, \method{executemany} and
582\method{executescript} methods of the \class{Connection} object, your code can
583be written more concisely, because you don't have to create the - often
584superfluous \class{Cursor} objects explicitly. Instead, the \class{Cursor}
585objects are created implicitly and these shortcut methods return the cursor
586objects. This way, you can for example execute a SELECT statement and iterate
587over it directly using only a single call on the \class{Connection} object.
588
589 \verbatiminput{sqlite3/shortcut_methods.py}
590
591\subsubsection{Accessing columns by name instead of by index}
592
593One cool feature of the \module{sqlite3} module is the builtin \class{sqlite3.Row} class
594designed to be used as a row factory.
595
596Rows wrapped with this class can be accessed both by index (like tuples) and
597case-insensitively by name:
598
599 \verbatiminput{sqlite3/rowclass.py}
600
601