blob: 1420ad7b072c64df7cbe398d8064485268b60295 [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
Georg Brandl26497d92008-10-08 17:20:20 +000030and call its :meth:`~Cursor.execute` method to perform SQL commands::
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
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
Georg Brandl26497d92008-10-08 17:20:20 +000055second argument to the cursor's :meth:`~Cursor.execute` method. (Other database modules
Georg Brandl8ec7f652007-08-15 14:28:01 +000056may 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
Georg Brandl26497d92008-10-08 17:20:20 +000074cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
75retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandle7a09902007-10-21 12:10:28 +000076matching 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
Gerhard Häringe11c9b32008-05-04 13:42:44 +0000117 column it returns. It will parse out the first word of the declared type,
118 i. e. for "integer primary key", it will parse out "integer", or for
119 "number(10)" it will parse out "number". Then for that column, it will look
120 into the converters dictionary and use the converter function registered for
121 that type there.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000122
123
124.. data:: PARSE_COLNAMES
125
126 This constant is meant to be used with the *detect_types* parameter of the
127 :func:`connect` function.
128
129 Setting this makes the SQLite interface parse the column name for each column it
130 returns. It will look for a string formed [mytype] in there, and then decide
131 that 'mytype' is the type of the column. It will try to find an entry of
132 'mytype' in the converters dictionary and then use the converter function found
Georg Brandl26497d92008-10-08 17:20:20 +0000133 there to return the value. The column name found in :attr:`Cursor.description`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000134 is only the first word of the column name, i. e. if you use something like
135 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
136 first blank for the column name: the column name would simply be "x".
137
138
139.. function:: connect(database[, timeout, isolation_level, detect_types, factory])
140
141 Opens a connection to the SQLite database file *database*. You can use
142 ``":memory:"`` to open a database connection to a database that resides in RAM
143 instead of on disk.
144
145 When a database is accessed by multiple connections, and one of the processes
146 modifies the database, the SQLite database is locked until that transaction is
147 committed. The *timeout* parameter specifies how long the connection should wait
148 for the lock to go away until raising an exception. The default for the timeout
149 parameter is 5.0 (five seconds).
150
151 For the *isolation_level* parameter, please see the
152 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
153
154 SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
155 you want to use other types you must add support for them yourself. The
156 *detect_types* parameter and the using custom **converters** registered with the
157 module-level :func:`register_converter` function allow you to easily do that.
158
159 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
160 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
161 type detection on.
162
163 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
164 connect call. You can, however, subclass the :class:`Connection` class and make
165 :func:`connect` use your class instead by providing your class for the *factory*
166 parameter.
167
168 Consult the section :ref:`sqlite3-types` of this manual for details.
169
170 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
171 overhead. If you want to explicitly set the number of statements that are cached
172 for the connection, you can set the *cached_statements* parameter. The currently
173 implemented default is to cache 100 statements.
174
175
176.. function:: register_converter(typename, callable)
177
178 Registers a callable to convert a bytestring from the database into a custom
179 Python type. The callable will be invoked for all database values that are of
180 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
181 function for how the type detection works. Note that the case of *typename* and
182 the name of the type in your query must match!
183
184
185.. function:: register_adapter(type, callable)
186
187 Registers a callable to convert the custom Python type *type* into one of
188 SQLite's supported types. The callable *callable* accepts as single parameter
189 the Python value, and must return a value of the following types: int, long,
190 float, str (UTF-8 encoded), unicode or buffer.
191
192
193.. function:: complete_statement(sql)
194
195 Returns :const:`True` if the string *sql* contains one or more complete SQL
196 statements terminated by semicolons. It does not verify that the SQL is
197 syntactically correct, only that there are no unclosed string literals and the
198 statement is terminated by a semicolon.
199
200 This can be used to build a shell for SQLite, as in the following example:
201
202
203 .. literalinclude:: ../includes/sqlite3/complete_statement.py
204
205
206.. function:: enable_callback_tracebacks(flag)
207
208 By default you will not get any tracebacks in user-defined functions,
209 aggregates, converters, authorizer callbacks etc. If you want to debug them, you
210 can call this function with *flag* as True. Afterwards, you will get tracebacks
211 from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
212 again.
213
214
215.. _sqlite3-connection-objects:
216
217Connection Objects
218------------------
219
Georg Brandl26497d92008-10-08 17:20:20 +0000220.. class:: Connection
221
222 A SQLite database connection has the following attributes and methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000223
224.. attribute:: Connection.isolation_level
225
Georg Brandl26497d92008-10-08 17:20:20 +0000226 Get or set the current isolation level. :const:`None` for autocommit mode or one of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000227 "DEFERRED", "IMMEDIATE" or "EXLUSIVE". See section
228 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
229
230
231.. method:: Connection.cursor([cursorClass])
232
233 The cursor method accepts a single optional parameter *cursorClass*. If
234 supplied, this must be a custom cursor class that extends
235 :class:`sqlite3.Cursor`.
236
237
Gerhard Häring41309302008-03-29 01:27:37 +0000238.. method:: Connection.commit()
239
240 This method commits the current transaction. If you don't call this method,
Georg Brandl26497d92008-10-08 17:20:20 +0000241 anything you did since the last call to ``commit()`` is not visible from from
Gerhard Häring41309302008-03-29 01:27:37 +0000242 other database connections. If you wonder why you don't see the data you've
243 written to the database, please check you didn't forget to call this method.
244
245.. method:: Connection.rollback()
246
247 This method rolls back any changes to the database since the last call to
248 :meth:`commit`.
249
250.. method:: Connection.close()
251
252 This closes the database connection. Note that this does not automatically
253 call :meth:`commit`. If you just close your database connection without
254 calling :meth:`commit` first, your changes will be lost!
255
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256.. method:: Connection.execute(sql, [parameters])
257
258 This is a nonstandard shortcut that creates an intermediate cursor object by
259 calling the cursor method, then calls the cursor's :meth:`execute` method with
260 the parameters given.
261
262
263.. method:: Connection.executemany(sql, [parameters])
264
265 This is a nonstandard shortcut that creates an intermediate cursor object by
266 calling the cursor method, then calls the cursor's :meth:`executemany` method
267 with the parameters given.
268
Georg Brandl8ec7f652007-08-15 14:28:01 +0000269.. method:: Connection.executescript(sql_script)
270
271 This is a nonstandard shortcut that creates an intermediate cursor object by
272 calling the cursor method, then calls the cursor's :meth:`executescript` method
273 with the parameters given.
274
275
276.. method:: Connection.create_function(name, num_params, func)
277
278 Creates a user-defined function that you can later use from within SQL
279 statements under the function name *name*. *num_params* is the number of
280 parameters the function accepts, and *func* is a Python callable that is called
281 as the SQL function.
282
283 The function can return any of the types supported by SQLite: unicode, str, int,
284 long, float, buffer and None.
285
286 Example:
287
288 .. literalinclude:: ../includes/sqlite3/md5func.py
289
290
291.. method:: Connection.create_aggregate(name, num_params, aggregate_class)
292
293 Creates a user-defined aggregate function.
294
295 The aggregate class must implement a ``step`` method, which accepts the number
296 of parameters *num_params*, and a ``finalize`` method which will return the
297 final result of the aggregate.
298
299 The ``finalize`` method can return any of the types supported by SQLite:
300 unicode, str, int, long, float, buffer and None.
301
302 Example:
303
304 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
305
306
307.. method:: Connection.create_collation(name, callable)
308
309 Creates a collation with the specified *name* and *callable*. The callable will
310 be passed two string arguments. It should return -1 if the first is ordered
311 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
312 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
313 your comparisons don't affect other SQL operations.
314
315 Note that the callable will get its parameters as Python bytestrings, which will
316 normally be encoded in UTF-8.
317
318 The following example shows a custom collation that sorts "the wrong way":
319
320 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
321
322 To remove a collation, call ``create_collation`` with None as callable::
323
324 con.create_collation("reverse", None)
325
326
327.. method:: Connection.interrupt()
328
329 You can call this method from a different thread to abort any queries that might
330 be executing on the connection. The query will then abort and the caller will
331 get an exception.
332
333
334.. method:: Connection.set_authorizer(authorizer_callback)
335
336 This routine registers a callback. The callback is invoked for each attempt to
337 access a column of a table in the database. The callback should return
338 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
339 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
340 column should be treated as a NULL value. These constants are available in the
341 :mod:`sqlite3` module.
342
343 The first argument to the callback signifies what kind of operation is to be
344 authorized. The second and third argument will be arguments or :const:`None`
345 depending on the first argument. The 4th argument is the name of the database
346 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
347 inner-most trigger or view that is responsible for the access attempt or
348 :const:`None` if this access attempt is directly from input SQL code.
349
350 Please consult the SQLite documentation about the possible values for the first
351 argument and the meaning of the second and third argument depending on the first
352 one. All necessary constants are available in the :mod:`sqlite3` module.
353
354
Gerhard Häring41309302008-03-29 01:27:37 +0000355.. method:: Connection.set_progress_handler(handler, n)
356
357 .. versionadded:: 2.6
358
359 This routine registers a callback. The callback is invoked for every *n*
360 instructions of the SQLite virtual machine. This is useful if you want to
361 get called from SQLite during long-running operations, for example to update
362 a GUI.
363
364 If you want to clear any previously installed progress handler, call the
365 method with :const:`None` for *handler*.
366
367
Georg Brandl8ec7f652007-08-15 14:28:01 +0000368.. attribute:: Connection.row_factory
369
370 You can change this attribute to a callable that accepts the cursor and the
371 original row as a tuple and will return the real result row. This way, you can
372 implement more advanced ways of returning results, such as returning an object
373 that can also access columns by name.
374
375 Example:
376
377 .. literalinclude:: ../includes/sqlite3/row_factory.py
378
379 If returning a tuple doesn't suffice and you want name-based access to
380 columns, you should consider setting :attr:`row_factory` to the
381 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
382 index-based and case-insensitive name-based access to columns with almost no
383 memory overhead. It will probably be better than your own custom
384 dictionary-based approach or even a db_row based solution.
385
Georg Brandlb19be572007-12-29 10:57:00 +0000386 .. XXX what's a db_row-based solution?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000387
388
389.. attribute:: Connection.text_factory
390
Georg Brandl26497d92008-10-08 17:20:20 +0000391 Using this attribute you can control what objects are returned for the ``TEXT``
392 data type. By default, this attribute is set to :class:`unicode` and the
393 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000394 return bytestrings instead, you can set it to :class:`str`.
395
396 For efficiency reasons, there's also a way to return Unicode objects only for
397 non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to
398 :const:`sqlite3.OptimizedUnicode`.
399
400 You can also set it to any other callable that accepts a single bytestring
401 parameter and returns the resulting object.
402
403 See the following example code for illustration:
404
405 .. literalinclude:: ../includes/sqlite3/text_factory.py
406
407
408.. attribute:: Connection.total_changes
409
410 Returns the total number of database rows that have been modified, inserted, or
411 deleted since the database connection was opened.
412
413
Gregory P. Smithb9803422008-03-28 08:32:09 +0000414.. attribute:: Connection.iterdump
415
416 Returns an iterator to dump the database in an SQL text format. Useful when
417 saving an in-memory database for later restoration. This function provides
418 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
419 shell.
420
421 .. versionadded:: 2.6
422
423 Example::
424
425 # Convert file existing_db.db to SQL dump file dump.sql
426 import sqlite3, os
427
428 con = sqlite3.connect('existing_db.db')
Andrew M. Kuchlingcd520232008-09-06 20:28:01 +0000429 full_dump = os.linesep.join(con.iterdump())
Gregory P. Smithb9803422008-03-28 08:32:09 +0000430 f = open('dump.sql', 'w')
431 f.writelines(full_dump)
432 f.close()
433
434
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435.. _sqlite3-cursor-objects:
436
437Cursor Objects
438--------------
439
Georg Brandl26497d92008-10-08 17:20:20 +0000440.. class:: Cursor
Georg Brandl8ec7f652007-08-15 14:28:01 +0000441
Georg Brandl26497d92008-10-08 17:20:20 +0000442 A SQLite database cursor has the following attributes and methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000443
444.. method:: Cursor.execute(sql, [parameters])
445
Georg Brandlf558d2e2008-01-19 20:53:07 +0000446 Executes an SQL statement. The SQL statement may be parametrized (i. e.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000447 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
448 kinds of placeholders: question marks (qmark style) and named placeholders
449 (named style).
450
451 This example shows how to use parameters with qmark style:
452
453 .. literalinclude:: ../includes/sqlite3/execute_1.py
454
455 This example shows how to use the named style:
456
457 .. literalinclude:: ../includes/sqlite3/execute_2.py
458
459 :meth:`execute` will only execute a single SQL statement. If you try to execute
460 more than one statement with it, it will raise a Warning. Use
461 :meth:`executescript` if you want to execute multiple SQL statements with one
462 call.
463
464
465.. method:: Cursor.executemany(sql, seq_of_parameters)
466
Georg Brandlf558d2e2008-01-19 20:53:07 +0000467 Executes an SQL command against all parameter sequences or mappings found in
Georg Brandle7a09902007-10-21 12:10:28 +0000468 the sequence *sql*. The :mod:`sqlite3` module also allows using an
469 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000470
471 .. literalinclude:: ../includes/sqlite3/executemany_1.py
472
Georg Brandlcf3fb252007-10-21 10:52:38 +0000473 Here's a shorter example using a :term:`generator`:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000474
475 .. literalinclude:: ../includes/sqlite3/executemany_2.py
476
477
478.. method:: Cursor.executescript(sql_script)
479
480 This is a nonstandard convenience method for executing multiple SQL statements
Georg Brandl26497d92008-10-08 17:20:20 +0000481 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
Georg Brandl8ec7f652007-08-15 14:28:01 +0000482 gets as a parameter.
483
484 *sql_script* can be a bytestring or a Unicode string.
485
486 Example:
487
488 .. literalinclude:: ../includes/sqlite3/executescript.py
489
490
Georg Brandlf558d2e2008-01-19 20:53:07 +0000491.. method:: Cursor.fetchone()
492
493 Fetches the next row of a query result set, returning a single sequence,
Georg Brandl26497d92008-10-08 17:20:20 +0000494 or :const:`None` when no more data is available.
Georg Brandlf558d2e2008-01-19 20:53:07 +0000495
496
497.. method:: Cursor.fetchmany([size=cursor.arraysize])
498
499 Fetches the next set of rows of a query result, returning a list. An empty
500 list is returned when no more rows are available.
501
502 The number of rows to fetch per call is specified by the *size* parameter.
503 If it is not given, the cursor's arraysize determines the number of rows
504 to be fetched. The method should try to fetch as many rows as indicated by
505 the size parameter. If this is not possible due to the specified number of
506 rows not being available, fewer rows may be returned.
507
508 Note there are performance considerations involved with the *size* parameter.
509 For optimal performance, it is usually best to use the arraysize attribute.
510 If the *size* parameter is used, then it is best for it to retain the same
511 value from one :meth:`fetchmany` call to the next.
512
513.. method:: Cursor.fetchall()
514
515 Fetches all (remaining) rows of a query result, returning a list. Note that
516 the cursor's arraysize attribute can affect the performance of this operation.
517 An empty list is returned when no rows are available.
518
519
Georg Brandl8ec7f652007-08-15 14:28:01 +0000520.. attribute:: Cursor.rowcount
521
522 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
523 attribute, the database engine's own support for the determination of "rows
524 affected"/"rows selected" is quirky.
525
Georg Brandl8ec7f652007-08-15 14:28:01 +0000526 For ``DELETE`` statements, SQLite reports :attr:`rowcount` as 0 if you make a
527 ``DELETE FROM table`` without any condition.
528
529 For :meth:`executemany` statements, the number of modifications are summed up
530 into :attr:`rowcount`.
531
532 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
Georg Brandl26497d92008-10-08 17:20:20 +0000533 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
534 last operation is not determinable by the interface".
Georg Brandl8ec7f652007-08-15 14:28:01 +0000535
Georg Brandl891f1d32007-08-23 20:40:01 +0000536 This includes ``SELECT`` statements because we cannot determine the number of
537 rows a query produced until all rows were fetched.
538
Gerhard Häringc15317e2008-03-29 19:11:52 +0000539.. attribute:: Cursor.lastrowid
540
541 This read-only attribute provides the rowid of the last modified row. It is
542 only set if you issued a ``INSERT`` statement using the :meth:`execute`
543 method. For operations other than ``INSERT`` or when :meth:`executemany` is
544 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000545
Georg Brandl26497d92008-10-08 17:20:20 +0000546.. attribute:: Cursor.description
547
548 This read-only attribute provides the column names of the last query. To
549 remain compatible with the Python DB API, it returns a 7-tuple for each
550 column where the last six items of each tuple are :const:`None`.
551
552 It is set for ``SELECT`` statements without any matching rows as well.
553
554.. _sqlite3-row-objects:
555
556Row Objects
557-----------
558
559.. class:: Row
560
561 A :class:`Row` instance serves as a highly optimized
562 :attr:`~Connection.row_factory` for :class:`Connection` objects.
563 It tries to mimic a tuple in most of its features.
564
565 It supports mapping access by column name and index, iteration,
566 representation, equality testing and :func:`len`.
567
568 If two :class:`Row` objects have exactly the same columns and their
569 members are equal, they compare equal.
570
571 .. versionchanged:: 2.6
572 Added iteration and equality (hashability).
573
574 .. method:: keys
575
576 This method returns a tuple of column names. Immediately after a query,
577 it is the first member of each tuple in :attr:`Cursor.description`.
578
579 .. versionadded:: 2.6
580
581Let's assume we initialize a table as in the example given above::
582
583 conn = sqlite3.connect(":memory:")
584 c = conn.cursor()
585 c.execute('''create table stocks
586 (date text, trans text, symbol text,
587 qty real, price real)''')
588 c.execute("""insert into stocks
589 values ('2006-01-05','BUY','RHAT',100,35.14)""")
590 conn.commit()
591 c.close()
592
593Now we plug :class:`Row` in::
594
595 >>> conn.row_factory = sqlite3.Row
596 >>> c = conn.cursor()
597 >>> c.execute('select * from stocks')
598 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
599 >>> r = c.fetchone()
600 >>> type(r)
601 <type 'sqlite3.Row'>
602 >>> r
603 (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)
604 >>> len(r)
605 5
606 >>> r[2]
607 u'RHAT'
608 >>> r.keys()
609 ['date', 'trans', 'symbol', 'qty', 'price']
610 >>> r['qty']
611 100.0
612 >>> for member in r: print member
613 ...
614 2006-01-05
615 BUY
616 RHAT
617 100.0
618 35.14
619
620
Georg Brandl8ec7f652007-08-15 14:28:01 +0000621.. _sqlite3-types:
622
623SQLite and Python types
624-----------------------
625
626
627Introduction
628^^^^^^^^^^^^
629
Georg Brandl26497d92008-10-08 17:20:20 +0000630SQLite natively supports the following types: ``NULL``, ``INTEGER``,
631``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000632
633The following Python types can thus be sent to SQLite without any problem:
634
Georg Brandl26497d92008-10-08 17:20:20 +0000635+-----------------------------+-------------+
636| Python type | SQLite type |
637+=============================+=============+
638| :const:`None` | ``NULL`` |
639+-----------------------------+-------------+
640| :class:`int` | ``INTEGER`` |
641+-----------------------------+-------------+
642| :class:`long` | ``INTEGER`` |
643+-----------------------------+-------------+
644| :class:`float` | ``REAL`` |
645+-----------------------------+-------------+
646| :class:`str` (UTF8-encoded) | ``TEXT`` |
647+-----------------------------+-------------+
648| :class:`unicode` | ``TEXT`` |
649+-----------------------------+-------------+
650| :class:`buffer` | ``BLOB`` |
651+-----------------------------+-------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000652
653This is how SQLite types are converted to Python types by default:
654
Georg Brandl26497d92008-10-08 17:20:20 +0000655+-------------+----------------------------------------------+
656| SQLite type | Python type |
657+=============+==============================================+
658| ``NULL`` | :const:`None` |
659+-------------+----------------------------------------------+
660| ``INTEGER`` | :class:`int` or :class:`long`, |
661| | depending on size |
662+-------------+----------------------------------------------+
663| ``REAL`` | :class:`float` |
664+-------------+----------------------------------------------+
665| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
666| | :class:`unicode` by default |
667+-------------+----------------------------------------------+
668| ``BLOB`` | :class:`buffer` |
669+-------------+----------------------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000670
671The type system of the :mod:`sqlite3` module is extensible in two ways: you can
672store additional Python types in a SQLite database via object adaptation, and
673you can let the :mod:`sqlite3` module convert SQLite types to different Python
674types via converters.
675
676
677Using adapters to store additional Python types in SQLite databases
678^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
679
680As described before, SQLite supports only a limited set of types natively. To
681use other Python types with SQLite, you must **adapt** them to one of the
682sqlite3 module's supported types for SQLite: one of NoneType, int, long, float,
683str, unicode, buffer.
684
685The :mod:`sqlite3` module uses Python object adaptation, as described in
686:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
687
688There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
689type to one of the supported ones.
690
691
692Letting your object adapt itself
693""""""""""""""""""""""""""""""""
694
695This is a good approach if you write the class yourself. Let's suppose you have
696a class like this::
697
698 class Point(object):
699 def __init__(self, x, y):
700 self.x, self.y = x, y
701
702Now you want to store the point in a single SQLite column. First you'll have to
703choose one of the supported types first to be used for representing the point.
704Let's just use str and separate the coordinates using a semicolon. Then you need
705to give your class a method ``__conform__(self, protocol)`` which must return
706the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
707
708.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
709
710
711Registering an adapter callable
712"""""""""""""""""""""""""""""""
713
714The other possibility is to create a function that converts the type to the
715string representation and register the function with :meth:`register_adapter`.
716
717.. note::
718
Georg Brandla7395032007-10-21 12:15:05 +0000719 The type/class to adapt must be a :term:`new-style class`, i. e. it must have
Georg Brandl8ec7f652007-08-15 14:28:01 +0000720 :class:`object` as one of its bases.
721
722.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
723
724The :mod:`sqlite3` module has two default adapters for Python's built-in
725:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
726we want to store :class:`datetime.datetime` objects not in ISO representation,
727but as a Unix timestamp.
728
729.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
730
731
732Converting SQLite values to custom Python types
733^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
734
735Writing an adapter lets you send custom Python types to SQLite. But to make it
736really useful we need to make the Python to SQLite to Python roundtrip work.
737
738Enter converters.
739
740Let's go back to the :class:`Point` class. We stored the x and y coordinates
741separated via semicolons as strings in SQLite.
742
743First, we'll define a converter function that accepts the string as a parameter
744and constructs a :class:`Point` object from it.
745
746.. note::
747
748 Converter functions **always** get called with a string, no matter under which
749 data type you sent the value to SQLite.
750
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751::
752
753 def convert_point(s):
754 x, y = map(float, s.split(";"))
755 return Point(x, y)
756
757Now you need to make the :mod:`sqlite3` module know that what you select from
758the database is actually a point. There are two ways of doing this:
759
760* Implicitly via the declared type
761
762* Explicitly via the column name
763
764Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
765for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
766
767The following example illustrates both approaches.
768
769.. literalinclude:: ../includes/sqlite3/converter_point.py
770
771
772Default adapters and converters
773^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
774
775There are default adapters for the date and datetime types in the datetime
776module. They will be sent as ISO dates/ISO timestamps to SQLite.
777
778The default converters are registered under the name "date" for
779:class:`datetime.date` and under the name "timestamp" for
780:class:`datetime.datetime`.
781
782This way, you can use date/timestamps from Python without any additional
783fiddling in most cases. The format of the adapters is also compatible with the
784experimental SQLite date/time functions.
785
786The following example demonstrates this.
787
788.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
789
790
791.. _sqlite3-controlling-transactions:
792
793Controlling Transactions
794------------------------
795
796By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandl26497d92008-10-08 17:20:20 +0000797Data Modification Language (DML) statement (i.e.
798``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
799implicitly before a non-DML, non-query statement (i. e.
800anything other than ``SELECT`` or the aforementioned).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000801
802So if you are within a transaction and issue a command like ``CREATE TABLE
803...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
804before executing that command. There are two reasons for doing that. The first
805is that some of these commands don't work within transactions. The other reason
806is that pysqlite needs to keep track of the transaction state (if a transaction
807is active or not).
808
Georg Brandl26497d92008-10-08 17:20:20 +0000809You can control which kind of ``BEGIN`` statements pysqlite implicitly executes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000810(or none at all) via the *isolation_level* parameter to the :func:`connect`
811call, or via the :attr:`isolation_level` property of connections.
812
813If you want **autocommit mode**, then set :attr:`isolation_level` to None.
814
815Otherwise leave it at its default, which will result in a plain "BEGIN"
816statement, or set it to one of SQLite's supported isolation levels: DEFERRED,
817IMMEDIATE or EXCLUSIVE.
818
Georg Brandl8ec7f652007-08-15 14:28:01 +0000819
820
821Using pysqlite efficiently
822--------------------------
823
824
825Using shortcut methods
826^^^^^^^^^^^^^^^^^^^^^^
827
828Using the nonstandard :meth:`execute`, :meth:`executemany` and
829:meth:`executescript` methods of the :class:`Connection` object, your code can
830be written more concisely because you don't have to create the (often
831superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
832objects are created implicitly and these shortcut methods return the cursor
Georg Brandl26497d92008-10-08 17:20:20 +0000833objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl8ec7f652007-08-15 14:28:01 +0000834directly using only a single call on the :class:`Connection` object.
835
836.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
837
838
839Accessing columns by name instead of by index
840^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
841
842One useful feature of the :mod:`sqlite3` module is the builtin
843:class:`sqlite3.Row` class designed to be used as a row factory.
844
845Rows wrapped with this class can be accessed both by index (like tuples) and
846case-insensitively by name:
847
848.. literalinclude:: ../includes/sqlite3/rowclass.py
849
Gerhard Häring41309302008-03-29 01:27:37 +0000850
851Using the connection as a context manager
852^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
853
854.. versionadded:: 2.6
855
856Connection objects can be used as context managers
857that automatically commit or rollback transactions. In the event of an
858exception, the transaction is rolled back; otherwise, the transaction is
859committed:
860
861.. literalinclude:: ../includes/sqlite3/ctx_manager.py