blob: 299be038fde4f00bf1e0edab3063ba6e49e662c7 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`sqlite3` --- DB-API 2.0 interface for SQLite databases
2============================================================
3
4.. module:: sqlite3
5 :synopsis: A DB-API 2.0 implementation using SQLite 3.x.
6.. sectionauthor:: Gerhard Häring <gh@ghaering.de>
7
8
Georg Brandl116aa622007-08-15 14:28:22 +00009SQLite is a C library that provides a lightweight disk-based database that
10doesn't require a separate server process and allows accessing the database
11using a nonstandard variant of the SQL query language. Some applications can use
12SQLite for internal data storage. It's also possible to prototype an
13application using SQLite and then port the code to a larger database such as
14PostgreSQL or Oracle.
15
Georg Brandl8a1e4c42009-05-25 21:13:36 +000016sqlite3 was written by Gerhard Häring and provides a SQL interface compliant
Georg Brandl116aa622007-08-15 14:28:22 +000017with the DB-API 2.0 specification described by :pep:`249`.
18
19To use the module, you must first create a :class:`Connection` object that
20represents the database. Here the data will be stored in the
21:file:`/tmp/example` file::
22
23 conn = sqlite3.connect('/tmp/example')
24
25You can also supply the special name ``:memory:`` to create a database in RAM.
26
27Once you have a :class:`Connection`, you can create a :class:`Cursor` object
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000028and call its :meth:`~Cursor.execute` method to perform SQL commands::
Georg Brandl116aa622007-08-15 14:28:22 +000029
30 c = conn.cursor()
31
32 # Create table
33 c.execute('''create table stocks
34 (date text, trans text, symbol text,
35 qty real, price real)''')
36
37 # Insert a row of data
38 c.execute("""insert into stocks
39 values ('2006-01-05','BUY','RHAT',100,35.14)""")
40
41 # Save (commit) the changes
42 conn.commit()
43
44 # We can also close the cursor if we are done with it
45 c.close()
46
47Usually your SQL operations will need to use values from Python variables. You
48shouldn't assemble your query using Python's string operations because doing so
49is insecure; it makes your program vulnerable to an SQL injection attack.
50
51Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
52wherever you want to use a value, and then provide a tuple of values as the
Georg Brandl8a1e4c42009-05-25 21:13:36 +000053second argument to the cursor's :meth:`~Cursor.execute` method. (Other database
54modules may use a different placeholder, such as ``%s`` or ``:1``.) For
55example::
Georg Brandl116aa622007-08-15 14:28:22 +000056
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
Georg Brandla971c652008-11-07 09:39:56 +000066 for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Georg Brandl116aa622007-08-15 14:28:22 +000067 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
68 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
Georg Brandla971c652008-11-07 09:39:56 +000069 ]:
Georg Brandl116aa622007-08-15 14:28:22 +000070 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
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000073cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
74retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandl9afde1c2007-11-01 20:32:30 +000075matching 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:
Ezio Melottib5845052009-09-13 05:49:25 +000082 ... print(row)
Georg Brandl116aa622007-08-15 14:28:22 +000083 ...
Ezio Melottib5845052009-09-13 05:49:25 +000084 ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
85 ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
86 ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
87 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.0)
Georg Brandl116aa622007-08-15 14:28:22 +000088 >>>
89
90
91.. seealso::
92
Benjamin Peterson2614cda2010-03-21 22:36:19 +000093 http://code.google.com/p/pysqlite/
Georg Brandl8a1e4c42009-05-25 21:13:36 +000094 The pysqlite web page -- sqlite3 is developed externally under the name
95 "pysqlite".
Georg Brandl116aa622007-08-15 14:28:22 +000096
97 http://www.sqlite.org
Georg Brandl8a1e4c42009-05-25 21:13:36 +000098 The SQLite web page; the documentation describes the syntax and the
99 available data types for the supported SQL dialect.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
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
Christian Heimes81ee3ef2008-05-04 22:42:01 +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 Brandl116aa622007-08-15 14:28:22 +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
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000133 there to return the value. The column name found in :attr:`Cursor.description`
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl1c616a52010-07-10 12:01:34 +0000139.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
Georg Brandl116aa622007-08-15 14:28:22 +0000140
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
Georg Brandl5c106642007-11-29 17:41:05 +0000189 the Python value, and must return a value of the following types: int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000190 float, str or bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
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
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000220.. class:: Connection
221
222 A SQLite database connection has the following attributes and methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224.. attribute:: Connection.isolation_level
225
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000226 Get or set the current isolation level. :const:`None` for autocommit mode or
227 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
Georg Brandl116aa622007-08-15 14:28:22 +0000228 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
229
R. David Murrayd35251d2010-06-01 01:32:12 +0000230.. attribute:: Connection.in_transaction
231
Benjamin Peterson5c5eb362010-06-06 02:40:38 +0000232 :const:`True` if a transaction is active (there are uncommitted changes),
R. David Murrayd35251d2010-06-01 01:32:12 +0000233 :const:`False` otherwise. Read-only attribute.
234
Georg Brandl67b21b72010-08-17 15:07:14 +0000235 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237.. method:: Connection.cursor([cursorClass])
238
239 The cursor method accepts a single optional parameter *cursorClass*. If
240 supplied, this must be a custom cursor class that extends
241 :class:`sqlite3.Cursor`.
242
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000243.. method:: Connection.commit()
244
245 This method commits the current transaction. If you don't call this method,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000246 anything you did since the last call to ``commit()`` is not visible from from
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000247 other database connections. If you wonder why you don't see the data you've
248 written to the database, please check you didn't forget to call this method.
249
250.. method:: Connection.rollback()
251
252 This method rolls back any changes to the database since the last call to
253 :meth:`commit`.
254
255.. method:: Connection.close()
256
257 This closes the database connection. Note that this does not automatically
258 call :meth:`commit`. If you just close your database connection without
259 calling :meth:`commit` first, your changes will be lost!
260
Georg Brandl116aa622007-08-15 14:28:22 +0000261.. method:: Connection.execute(sql, [parameters])
262
263 This is a nonstandard shortcut that creates an intermediate cursor object by
Georg Brandl96115fb22010-10-17 09:33:24 +0000264 calling the cursor method, then calls the cursor's :meth:`execute
265 <Cursor.execute>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267
268.. method:: Connection.executemany(sql, [parameters])
269
270 This is a nonstandard shortcut that creates an intermediate cursor object by
Georg Brandl96115fb22010-10-17 09:33:24 +0000271 calling the cursor method, then calls the cursor's :meth:`executemany
272 <Cursor.executemany>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000273
274
275.. method:: Connection.executescript(sql_script)
276
277 This is a nonstandard shortcut that creates an intermediate cursor object by
Georg Brandl96115fb22010-10-17 09:33:24 +0000278 calling the cursor method, then calls the cursor's :meth:`executescript
279 <Cursor.executescript>` method with the parameters given.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281
282.. method:: Connection.create_function(name, num_params, func)
283
284 Creates a user-defined function that you can later use from within SQL
285 statements under the function name *name*. *num_params* is the number of
286 parameters the function accepts, and *func* is a Python callable that is called
287 as the SQL function.
288
Georg Brandlf6945182008-02-01 11:56:49 +0000289 The function can return any of the types supported by SQLite: bytes, str, int,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000290 float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000291
292 Example:
293
294 .. literalinclude:: ../includes/sqlite3/md5func.py
295
296
297.. method:: Connection.create_aggregate(name, num_params, aggregate_class)
298
299 Creates a user-defined aggregate function.
300
301 The aggregate class must implement a ``step`` method, which accepts the number
302 of parameters *num_params*, and a ``finalize`` method which will return the
303 final result of the aggregate.
304
305 The ``finalize`` method can return any of the types supported by SQLite:
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000306 bytes, str, int, float and None.
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308 Example:
309
310 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
311
312
313.. method:: Connection.create_collation(name, callable)
314
315 Creates a collation with the specified *name* and *callable*. The callable will
316 be passed two string arguments. It should return -1 if the first is ordered
317 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
318 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
319 your comparisons don't affect other SQL operations.
320
321 Note that the callable will get its parameters as Python bytestrings, which will
322 normally be encoded in UTF-8.
323
324 The following example shows a custom collation that sorts "the wrong way":
325
326 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
327
328 To remove a collation, call ``create_collation`` with None as callable::
329
330 con.create_collation("reverse", None)
331
332
333.. method:: Connection.interrupt()
334
335 You can call this method from a different thread to abort any queries that might
336 be executing on the connection. The query will then abort and the caller will
337 get an exception.
338
339
340.. method:: Connection.set_authorizer(authorizer_callback)
341
342 This routine registers a callback. The callback is invoked for each attempt to
343 access a column of a table in the database. The callback should return
344 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
345 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
346 column should be treated as a NULL value. These constants are available in the
347 :mod:`sqlite3` module.
348
349 The first argument to the callback signifies what kind of operation is to be
350 authorized. The second and third argument will be arguments or :const:`None`
351 depending on the first argument. The 4th argument is the name of the database
352 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
353 inner-most trigger or view that is responsible for the access attempt or
354 :const:`None` if this access attempt is directly from input SQL code.
355
356 Please consult the SQLite documentation about the possible values for the first
357 argument and the meaning of the second and third argument depending on the first
358 one. All necessary constants are available in the :mod:`sqlite3` module.
359
360
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000361.. method:: Connection.set_progress_handler(handler, n)
362
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000363 This routine registers a callback. The callback is invoked for every *n*
364 instructions of the SQLite virtual machine. This is useful if you want to
365 get called from SQLite during long-running operations, for example to update
366 a GUI.
367
368 If you want to clear any previously installed progress handler, call the
369 method with :const:`None` for *handler*.
370
371
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200372.. method:: Connection.set_trace_callback(trace_callback)
373
374 Registers *trace_callback* to be called for each SQL statement that is
375 actually executed by the SQLite backend.
376
377 The only argument passed to the callback is the statement (as string) that
378 is being executed. The return value of the callback is ignored. Note that
379 the backend does not only run statements passed to the :meth:`Cursor.execute`
380 methods. Other sources include the transaction management of the Python
381 module and the execution of triggers defined in the current database.
382
383 Passing :const:`None` as *trace_callback* will disable the trace callback.
384
385 .. versionadded:: 3.3
386
387
Gerhard Häringf9cee222010-03-05 15:20:03 +0000388.. method:: Connection.enable_load_extension(enabled)
389
Gerhard Häringf9cee222010-03-05 15:20:03 +0000390 This routine allows/disallows the SQLite engine to load SQLite extensions
391 from shared libraries. SQLite extensions can define new functions,
Georg Brandl96115fb22010-10-17 09:33:24 +0000392 aggregates or whole new virtual table implementations. One well-known
Gerhard Häringf9cee222010-03-05 15:20:03 +0000393 extension is the fulltext-search extension distributed with SQLite.
394
Georg Brandl67b21b72010-08-17 15:07:14 +0000395 .. versionadded:: 3.2
396
Gerhard Häringf9cee222010-03-05 15:20:03 +0000397 .. literalinclude:: ../includes/sqlite3/load_extension.py
398
Georg Brandl96115fb22010-10-17 09:33:24 +0000399 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringe0941c52010-10-03 21:47:06 +0000400
Gerhard Häringf9cee222010-03-05 15:20:03 +0000401.. method:: Connection.load_extension(path)
402
Georg Brandl96115fb22010-10-17 09:33:24 +0000403 This routine loads a SQLite extension from a shared library. You have to
404 enable extension loading with :meth:`enable_load_extension` before you can
405 use this routine.
Gerhard Häringf9cee222010-03-05 15:20:03 +0000406
Georg Brandl67b21b72010-08-17 15:07:14 +0000407 .. versionadded:: 3.2
408
Georg Brandl96115fb22010-10-17 09:33:24 +0000409 Loadable extensions are disabled by default. See [#f1]_.
Gerhard Häringe0941c52010-10-03 21:47:06 +0000410
Georg Brandl116aa622007-08-15 14:28:22 +0000411.. attribute:: Connection.row_factory
412
413 You can change this attribute to a callable that accepts the cursor and the
414 original row as a tuple and will return the real result row. This way, you can
415 implement more advanced ways of returning results, such as returning an object
416 that can also access columns by name.
417
418 Example:
419
420 .. literalinclude:: ../includes/sqlite3/row_factory.py
421
422 If returning a tuple doesn't suffice and you want name-based access to
423 columns, you should consider setting :attr:`row_factory` to the
424 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
425 index-based and case-insensitive name-based access to columns with almost no
426 memory overhead. It will probably be better than your own custom
427 dictionary-based approach or even a db_row based solution.
428
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000429 .. XXX what's a db_row-based solution?
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431
432.. attribute:: Connection.text_factory
433
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000434 Using this attribute you can control what objects are returned for the ``TEXT``
435 data type. By default, this attribute is set to :class:`str` and the
436 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
Georg Brandlf6945182008-02-01 11:56:49 +0000437 return bytestrings instead, you can set it to :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000438
Georg Brandlf6945182008-02-01 11:56:49 +0000439 For efficiency reasons, there's also a way to return :class:`str` objects
440 only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
441 this attribute to :const:`sqlite3.OptimizedUnicode`.
Georg Brandl116aa622007-08-15 14:28:22 +0000442
443 You can also set it to any other callable that accepts a single bytestring
444 parameter and returns the resulting object.
445
446 See the following example code for illustration:
447
448 .. literalinclude:: ../includes/sqlite3/text_factory.py
449
450
451.. attribute:: Connection.total_changes
452
453 Returns the total number of database rows that have been modified, inserted, or
454 deleted since the database connection was opened.
455
456
Christian Heimesbbe741d2008-03-28 10:53:29 +0000457.. attribute:: Connection.iterdump
458
459 Returns an iterator to dump the database in an SQL text format. Useful when
460 saving an in-memory database for later restoration. This function provides
461 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
462 shell.
463
Christian Heimesbbe741d2008-03-28 10:53:29 +0000464 Example::
465
466 # Convert file existing_db.db to SQL dump file dump.sql
467 import sqlite3, os
468
469 con = sqlite3.connect('existing_db.db')
Georg Brandla971c652008-11-07 09:39:56 +0000470 with open('dump.sql', 'w') as f:
471 for line in con.iterdump():
472 f.write('%s\n' % line)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000473
474
Georg Brandl116aa622007-08-15 14:28:22 +0000475.. _sqlite3-cursor-objects:
476
477Cursor Objects
478--------------
479
Georg Brandl96115fb22010-10-17 09:33:24 +0000480.. class:: Cursor
Georg Brandl116aa622007-08-15 14:28:22 +0000481
Georg Brandl96115fb22010-10-17 09:33:24 +0000482 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484.. method:: Cursor.execute(sql, [parameters])
485
Christian Heimesfdab48e2008-01-20 09:06:41 +0000486 Executes an SQL statement. The SQL statement may be parametrized (i. e.
Georg Brandl116aa622007-08-15 14:28:22 +0000487 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
488 kinds of placeholders: question marks (qmark style) and named placeholders
489 (named style).
490
491 This example shows how to use parameters with qmark style:
492
493 .. literalinclude:: ../includes/sqlite3/execute_1.py
494
495 This example shows how to use the named style:
496
497 .. literalinclude:: ../includes/sqlite3/execute_2.py
498
499 :meth:`execute` will only execute a single SQL statement. If you try to execute
500 more than one statement with it, it will raise a Warning. Use
501 :meth:`executescript` if you want to execute multiple SQL statements with one
502 call.
503
504
505.. method:: Cursor.executemany(sql, seq_of_parameters)
506
Christian Heimesfdab48e2008-01-20 09:06:41 +0000507 Executes an SQL command against all parameter sequences or mappings found in
Georg Brandl9afde1c2007-11-01 20:32:30 +0000508 the sequence *sql*. The :mod:`sqlite3` module also allows using an
509 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000510
511 .. literalinclude:: ../includes/sqlite3/executemany_1.py
512
Georg Brandl9afde1c2007-11-01 20:32:30 +0000513 Here's a shorter example using a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515 .. literalinclude:: ../includes/sqlite3/executemany_2.py
516
517
518.. method:: Cursor.executescript(sql_script)
519
520 This is a nonstandard convenience method for executing multiple SQL statements
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000521 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
Georg Brandl116aa622007-08-15 14:28:22 +0000522 gets as a parameter.
523
Georg Brandlf6945182008-02-01 11:56:49 +0000524 *sql_script* can be an instance of :class:`str` or :class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526 Example:
527
528 .. literalinclude:: ../includes/sqlite3/executescript.py
529
530
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000531.. method:: Cursor.fetchone()
532
Christian Heimesfdab48e2008-01-20 09:06:41 +0000533 Fetches the next row of a query result set, returning a single sequence,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000534 or :const:`None` when no more data is available.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000535
536
537.. method:: Cursor.fetchmany([size=cursor.arraysize])
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000538
Christian Heimesfdab48e2008-01-20 09:06:41 +0000539 Fetches the next set of rows of a query result, returning a list. An empty
540 list is returned when no more rows are available.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000541
Christian Heimesfdab48e2008-01-20 09:06:41 +0000542 The number of rows to fetch per call is specified by the *size* parameter.
543 If it is not given, the cursor's arraysize determines the number of rows
544 to be fetched. The method should try to fetch as many rows as indicated by
545 the size parameter. If this is not possible due to the specified number of
546 rows not being available, fewer rows may be returned.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000547
Christian Heimesfdab48e2008-01-20 09:06:41 +0000548 Note there are performance considerations involved with the *size* parameter.
549 For optimal performance, it is usually best to use the arraysize attribute.
550 If the *size* parameter is used, then it is best for it to retain the same
551 value from one :meth:`fetchmany` call to the next.
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000552
553.. method:: Cursor.fetchall()
Christian Heimesfdab48e2008-01-20 09:06:41 +0000554
555 Fetches all (remaining) rows of a query result, returning a list. Note that
556 the cursor's arraysize attribute can affect the performance of this operation.
557 An empty list is returned when no rows are available.
558
559
Georg Brandl116aa622007-08-15 14:28:22 +0000560.. attribute:: Cursor.rowcount
561
562 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
563 attribute, the database engine's own support for the determination of "rows
564 affected"/"rows selected" is quirky.
565
Georg Brandl116aa622007-08-15 14:28:22 +0000566 For ``DELETE`` statements, SQLite reports :attr:`rowcount` as 0 if you make a
567 ``DELETE FROM table`` without any condition.
568
569 For :meth:`executemany` statements, the number of modifications are summed up
570 into :attr:`rowcount`.
571
572 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000573 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
574 last operation is not determinable by the interface".
Georg Brandl116aa622007-08-15 14:28:22 +0000575
Guido van Rossum04110fb2007-08-24 16:32:05 +0000576 This includes ``SELECT`` statements because we cannot determine the number of
577 rows a query produced until all rows were fetched.
578
Gerhard Häringd3372792008-03-29 19:13:55 +0000579.. attribute:: Cursor.lastrowid
580
581 This read-only attribute provides the rowid of the last modified row. It is
582 only set if you issued a ``INSERT`` statement using the :meth:`execute`
583 method. For operations other than ``INSERT`` or when :meth:`executemany` is
584 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl116aa622007-08-15 14:28:22 +0000585
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000586.. attribute:: Cursor.description
587
588 This read-only attribute provides the column names of the last query. To
589 remain compatible with the Python DB API, it returns a 7-tuple for each
Georg Brandl48310cd2009-01-03 21:18:54 +0000590 column where the last six items of each tuple are :const:`None`.
591
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000592 It is set for ``SELECT`` statements without any matching rows as well.
593
594.. _sqlite3-row-objects:
595
596Row Objects
597-----------
598
599.. class:: Row
600
601 A :class:`Row` instance serves as a highly optimized
Georg Brandl48310cd2009-01-03 21:18:54 +0000602 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000603 It tries to mimic a tuple in most of its features.
604
605 It supports mapping access by column name and index, iteration,
606 representation, equality testing and :func:`len`.
607
608 If two :class:`Row` objects have exactly the same columns and their
609 members are equal, they compare equal.
Georg Brandl48310cd2009-01-03 21:18:54 +0000610
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000611 .. method:: keys
612
613 This method returns a tuple of column names. Immediately after a query,
614 it is the first member of each tuple in :attr:`Cursor.description`.
615
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000616Let's assume we initialize a table as in the example given above::
617
Senthil Kumaran946eb862011-07-03 10:17:22 -0700618 conn = sqlite3.connect(":memory:")
619 c = conn.cursor()
620 c.execute('''create table stocks
621 (date text, trans text, symbol text,
622 qty real, price real)''')
623 c.execute("""insert into stocks
624 values ('2006-01-05','BUY','RHAT',100,35.14)""")
625 conn.commit()
626 c.close()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000627
628Now we plug :class:`Row` in::
629
Senthil Kumaran946eb862011-07-03 10:17:22 -0700630 >>> conn.row_factory = sqlite3.Row
631 >>> c = conn.cursor()
632 >>> c.execute('select * from stocks')
633 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
634 >>> r = c.fetchone()
635 >>> type(r)
636 <class 'sqlite3.Row'>
637 >>> tuple(r)
638 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
639 >>> len(r)
640 5
641 >>> r[2]
642 'RHAT'
643 >>> r.keys()
644 ['date', 'trans', 'symbol', 'qty', 'price']
645 >>> r['qty']
646 100.0
647 >>> for member in r:
648 ... print(member)
649 ...
650 2006-01-05
651 BUY
652 RHAT
653 100.0
654 35.14
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000655
656
Georg Brandl116aa622007-08-15 14:28:22 +0000657.. _sqlite3-types:
658
659SQLite and Python types
660-----------------------
661
662
663Introduction
664^^^^^^^^^^^^
665
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000666SQLite natively supports the following types: ``NULL``, ``INTEGER``,
667``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl116aa622007-08-15 14:28:22 +0000668
669The following Python types can thus be sent to SQLite without any problem:
670
Georg Brandlf6945182008-02-01 11:56:49 +0000671+-------------------------------+-------------+
672| Python type | SQLite type |
673+===============================+=============+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000674| :const:`None` | ``NULL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000675+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000676| :class:`int` | ``INTEGER`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000677+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000678| :class:`float` | ``REAL`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000679+-------------------------------+-------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000680| :class:`str` | ``TEXT`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000681+-------------------------------+-------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000682| :class:`bytes` | ``BLOB`` |
Georg Brandlf6945182008-02-01 11:56:49 +0000683+-------------------------------+-------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000684
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000685
Georg Brandl116aa622007-08-15 14:28:22 +0000686This is how SQLite types are converted to Python types by default:
687
688+-------------+---------------------------------------------+
689| SQLite type | Python type |
690+=============+=============================================+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000691| ``NULL`` | :const:`None` |
Georg Brandl116aa622007-08-15 14:28:22 +0000692+-------------+---------------------------------------------+
Ezio Melottib5845052009-09-13 05:49:25 +0000693| ``INTEGER`` | :class:`int` |
Georg Brandl116aa622007-08-15 14:28:22 +0000694+-------------+---------------------------------------------+
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000695| ``REAL`` | :class:`float` |
Georg Brandl116aa622007-08-15 14:28:22 +0000696+-------------+---------------------------------------------+
Georg Brandlf6945182008-02-01 11:56:49 +0000697| ``TEXT`` | depends on text_factory, str by default |
Georg Brandl116aa622007-08-15 14:28:22 +0000698+-------------+---------------------------------------------+
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000699| ``BLOB`` | :class:`bytes` |
Georg Brandl116aa622007-08-15 14:28:22 +0000700+-------------+---------------------------------------------+
701
702The type system of the :mod:`sqlite3` module is extensible in two ways: you can
703store additional Python types in a SQLite database via object adaptation, and
704you can let the :mod:`sqlite3` module convert SQLite types to different Python
705types via converters.
706
707
708Using adapters to store additional Python types in SQLite databases
709^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
710
711As described before, SQLite supports only a limited set of types natively. To
712use other Python types with SQLite, you must **adapt** them to one of the
Georg Brandl5c106642007-11-29 17:41:05 +0000713sqlite3 module's supported types for SQLite: one of NoneType, int, float,
Antoine Pitrouf06917e2010-02-02 23:00:29 +0000714str, bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000715
716The :mod:`sqlite3` module uses Python object adaptation, as described in
717:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
718
719There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
720type to one of the supported ones.
721
722
723Letting your object adapt itself
724""""""""""""""""""""""""""""""""
725
726This is a good approach if you write the class yourself. Let's suppose you have
727a class like this::
728
Éric Araujo28053fb2010-11-22 03:09:19 +0000729 class Point:
Georg Brandl116aa622007-08-15 14:28:22 +0000730 def __init__(self, x, y):
731 self.x, self.y = x, y
732
733Now you want to store the point in a single SQLite column. First you'll have to
734choose one of the supported types first to be used for representing the point.
735Let's just use str and separate the coordinates using a semicolon. Then you need
736to give your class a method ``__conform__(self, protocol)`` which must return
737the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
738
739.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
740
741
742Registering an adapter callable
743"""""""""""""""""""""""""""""""
744
745The other possibility is to create a function that converts the type to the
746string representation and register the function with :meth:`register_adapter`.
747
Georg Brandl116aa622007-08-15 14:28:22 +0000748.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
749
750The :mod:`sqlite3` module has two default adapters for Python's built-in
751:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
752we want to store :class:`datetime.datetime` objects not in ISO representation,
753but as a Unix timestamp.
754
755.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
756
757
758Converting SQLite values to custom Python types
759^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
760
761Writing an adapter lets you send custom Python types to SQLite. But to make it
762really useful we need to make the Python to SQLite to Python roundtrip work.
763
764Enter converters.
765
766Let's go back to the :class:`Point` class. We stored the x and y coordinates
767separated via semicolons as strings in SQLite.
768
769First, we'll define a converter function that accepts the string as a parameter
770and constructs a :class:`Point` object from it.
771
772.. note::
773
774 Converter functions **always** get called with a string, no matter under which
775 data type you sent the value to SQLite.
776
Georg Brandl116aa622007-08-15 14:28:22 +0000777::
778
779 def convert_point(s):
780 x, y = map(float, s.split(";"))
781 return Point(x, y)
782
783Now you need to make the :mod:`sqlite3` module know that what you select from
784the database is actually a point. There are two ways of doing this:
785
786* Implicitly via the declared type
787
788* Explicitly via the column name
789
790Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
791for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
792
793The following example illustrates both approaches.
794
795.. literalinclude:: ../includes/sqlite3/converter_point.py
796
797
798Default adapters and converters
799^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
800
801There are default adapters for the date and datetime types in the datetime
802module. They will be sent as ISO dates/ISO timestamps to SQLite.
803
804The default converters are registered under the name "date" for
805:class:`datetime.date` and under the name "timestamp" for
806:class:`datetime.datetime`.
807
808This way, you can use date/timestamps from Python without any additional
809fiddling in most cases. The format of the adapters is also compatible with the
810experimental SQLite date/time functions.
811
812The following example demonstrates this.
813
814.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
815
816
817.. _sqlite3-controlling-transactions:
818
819Controlling Transactions
820------------------------
821
822By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandl48310cd2009-01-03 21:18:54 +0000823Data Modification Language (DML) statement (i.e.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000824``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
825implicitly before a non-DML, non-query statement (i. e.
826anything other than ``SELECT`` or the aforementioned).
Georg Brandl116aa622007-08-15 14:28:22 +0000827
828So if you are within a transaction and issue a command like ``CREATE TABLE
829...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
830before executing that command. There are two reasons for doing that. The first
831is that some of these commands don't work within transactions. The other reason
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000832is that sqlite3 needs to keep track of the transaction state (if a transaction
R. David Murrayd35251d2010-06-01 01:32:12 +0000833is active or not). The current transaction state is exposed through the
834:attr:`Connection.in_transaction` attribute of the connection object.
Georg Brandl116aa622007-08-15 14:28:22 +0000835
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000836You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl116aa622007-08-15 14:28:22 +0000837(or none at all) via the *isolation_level* parameter to the :func:`connect`
838call, or via the :attr:`isolation_level` property of connections.
839
840If you want **autocommit mode**, then set :attr:`isolation_level` to None.
841
842Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandla971c652008-11-07 09:39:56 +0000843statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
844"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl116aa622007-08-15 14:28:22 +0000845
Georg Brandl116aa622007-08-15 14:28:22 +0000846
847
Georg Brandl8a1e4c42009-05-25 21:13:36 +0000848Using :mod:`sqlite3` efficiently
849--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851
852Using shortcut methods
853^^^^^^^^^^^^^^^^^^^^^^
854
855Using the nonstandard :meth:`execute`, :meth:`executemany` and
856:meth:`executescript` methods of the :class:`Connection` object, your code can
857be written more concisely because you don't have to create the (often
858superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
859objects are created implicitly and these shortcut methods return the cursor
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000860objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl116aa622007-08-15 14:28:22 +0000861directly using only a single call on the :class:`Connection` object.
862
863.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
864
865
866Accessing columns by name instead of by index
867^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
868
Georg Brandl22b34312009-07-26 14:54:51 +0000869One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000870:class:`sqlite3.Row` class designed to be used as a row factory.
871
872Rows wrapped with this class can be accessed both by index (like tuples) and
873case-insensitively by name:
874
875.. literalinclude:: ../includes/sqlite3/rowclass.py
876
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000877
878Using the connection as a context manager
879^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
880
Gerhard Häring0d7d6cf2008-03-29 01:32:44 +0000881Connection objects can be used as context managers
882that automatically commit or rollback transactions. In the event of an
883exception, the transaction is rolled back; otherwise, the transaction is
884committed:
885
886.. literalinclude:: ../includes/sqlite3/ctx_manager.py
Gerhard Häringc34d76c2010-08-06 06:12:05 +0000887
888
889Common issues
890-------------
891
892Multithreading
893^^^^^^^^^^^^^^
894
895Older SQLite versions had issues with sharing connections between threads.
896That's why the Python module disallows sharing connections and cursors between
897threads. If you still try to do so, you will get an exception at runtime.
898
899The only exception is calling the :meth:`~Connection.interrupt` method, which
900only makes sense to call from a different thread.
901
Gerhard Häringe0941c52010-10-03 21:47:06 +0000902.. rubric:: Footnotes
903
904.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumaran946eb862011-07-03 10:17:22 -0700905 default, because some platforms (notably Mac OS X) have SQLite
906 libraries which are compiled without this feature. To get loadable
907 extension support, you must pass --enable-loadable-sqlite-extensions to
908 configure.