blob: b4d58b9b6890ebe8c80bd026c993143f19559ce1 [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
Georg Brandl498a9b32009-05-20 18:31:14 +000018sqlite3 was written by Gerhard Häring and provides a SQL interface compliant
Georg Brandl8ec7f652007-08-15 14:28:01 +000019with 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
Raymond Hettinger81a55c02012-02-01 13:32:45 -080025 import sqlite3
Georg Brandl8ec7f652007-08-15 14:28:01 +000026 conn = sqlite3.connect('/tmp/example')
27
28You can also supply the special name ``:memory:`` to create a database in RAM.
29
30Once you have a :class:`Connection`, you can create a :class:`Cursor` object
Georg Brandl26497d92008-10-08 17:20:20 +000031and call its :meth:`~Cursor.execute` method to perform SQL commands::
Georg Brandl8ec7f652007-08-15 14:28:01 +000032
33 c = conn.cursor()
34
35 # Create table
36 c.execute('''create table stocks
37 (date text, trans text, symbol text,
38 qty real, price real)''')
39
40 # Insert a row of data
41 c.execute("""insert into stocks
42 values ('2006-01-05','BUY','RHAT',100,35.14)""")
43
44 # Save (commit) the changes
45 conn.commit()
46
47 # We can also close the cursor if we are done with it
48 c.close()
49
50Usually your SQL operations will need to use values from Python variables. You
51shouldn't assemble your query using Python's string operations because doing so
52is insecure; it makes your program vulnerable to an SQL injection attack.
53
54Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
55wherever you want to use a value, and then provide a tuple of values as the
Georg Brandl498a9b32009-05-20 18:31:14 +000056second argument to the cursor's :meth:`~Cursor.execute` method. (Other database
57modules may use a different placeholder, such as ``%s`` or ``:1``.) For
58example::
Georg Brandl8ec7f652007-08-15 14:28:01 +000059
60 # Never do this -- insecure!
61 symbol = 'IBM'
62 c.execute("... where symbol = '%s'" % symbol)
63
64 # Do this instead
65 t = (symbol,)
66 c.execute('select * from stocks where symbol=?', t)
67
68 # Larger example
Georg Brandlb9bfea72008-11-06 10:19:11 +000069 for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Raymond Hettingera0ff91c2012-01-10 09:51:51 +000070 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
Georg Brandl8ec7f652007-08-15 14:28:01 +000071 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
Georg Brandlb9bfea72008-11-06 10:19:11 +000072 ]:
Georg Brandl8ec7f652007-08-15 14:28:01 +000073 c.execute('insert into stocks values (?,?,?,?,?)', t)
74
Georg Brandle7a09902007-10-21 12:10:28 +000075To retrieve data after executing a SELECT statement, you can either treat the
Georg Brandl26497d92008-10-08 17:20:20 +000076cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
77retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
Georg Brandle7a09902007-10-21 12:10:28 +000078matching rows.
Georg Brandl8ec7f652007-08-15 14:28:01 +000079
80This example uses the iterator form::
81
82 >>> c = conn.cursor()
83 >>> c.execute('select * from stocks order by price')
84 >>> for row in c:
85 ... print row
86 ...
Mark Dickinson6b87f112009-11-24 14:27:02 +000087 (u'2006-01-05', u'BUY', u'RHAT', 100, 35.14)
Georg Brandl8ec7f652007-08-15 14:28:01 +000088 (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
89 (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
Raymond Hettingera0ff91c2012-01-10 09:51:51 +000090 (u'2006-04-05', u'BUY', u'MSFT', 1000, 72.0)
Georg Brandl8ec7f652007-08-15 14:28:01 +000091 >>>
92
93
94.. seealso::
95
Michael Foordabe63312010-03-02 14:22:15 +000096 http://code.google.com/p/pysqlite/
Georg Brandl498a9b32009-05-20 18:31:14 +000097 The pysqlite web page -- sqlite3 is developed externally under the name
98 "pysqlite".
Georg Brandl8ec7f652007-08-15 14:28:01 +000099
100 http://www.sqlite.org
Georg Brandl498a9b32009-05-20 18:31:14 +0000101 The SQLite web page; the documentation describes the syntax and the
102 available data types for the supported SQL dialect.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103
104 :pep:`249` - Database API Specification 2.0
105 PEP written by Marc-André Lemburg.
106
107
108.. _sqlite3-module-contents:
109
110Module functions and constants
111------------------------------
112
113
114.. data:: PARSE_DECLTYPES
115
116 This constant is meant to be used with the *detect_types* parameter of the
117 :func:`connect` function.
118
119 Setting it makes the :mod:`sqlite3` module parse the declared type for each
Gerhard Häringe11c9b32008-05-04 13:42:44 +0000120 column it returns. It will parse out the first word of the declared type,
121 i. e. for "integer primary key", it will parse out "integer", or for
122 "number(10)" it will parse out "number". Then for that column, it will look
123 into the converters dictionary and use the converter function registered for
124 that type there.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000125
126
127.. data:: PARSE_COLNAMES
128
129 This constant is meant to be used with the *detect_types* parameter of the
130 :func:`connect` function.
131
132 Setting this makes the SQLite interface parse the column name for each column it
133 returns. It will look for a string formed [mytype] in there, and then decide
134 that 'mytype' is the type of the column. It will try to find an entry of
135 'mytype' in the converters dictionary and then use the converter function found
Georg Brandl26497d92008-10-08 17:20:20 +0000136 there to return the value. The column name found in :attr:`Cursor.description`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000137 is only the first word of the column name, i. e. if you use something like
138 ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
139 first blank for the column name: the column name would simply be "x".
140
141
Georg Brandle85e1ae2010-10-06 09:17:24 +0000142.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143
144 Opens a connection to the SQLite database file *database*. You can use
145 ``":memory:"`` to open a database connection to a database that resides in RAM
146 instead of on disk.
147
148 When a database is accessed by multiple connections, and one of the processes
149 modifies the database, the SQLite database is locked until that transaction is
150 committed. The *timeout* parameter specifies how long the connection should wait
151 for the lock to go away until raising an exception. The default for the timeout
152 parameter is 5.0 (five seconds).
153
154 For the *isolation_level* parameter, please see the
155 :attr:`Connection.isolation_level` property of :class:`Connection` objects.
156
157 SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
158 you want to use other types you must add support for them yourself. The
159 *detect_types* parameter and the using custom **converters** registered with the
160 module-level :func:`register_converter` function allow you to easily do that.
161
162 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
163 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
164 type detection on.
165
166 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
167 connect call. You can, however, subclass the :class:`Connection` class and make
168 :func:`connect` use your class instead by providing your class for the *factory*
169 parameter.
170
171 Consult the section :ref:`sqlite3-types` of this manual for details.
172
173 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
174 overhead. If you want to explicitly set the number of statements that are cached
175 for the connection, you can set the *cached_statements* parameter. The currently
176 implemented default is to cache 100 statements.
177
178
179.. function:: register_converter(typename, callable)
180
181 Registers a callable to convert a bytestring from the database into a custom
182 Python type. The callable will be invoked for all database values that are of
183 the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
184 function for how the type detection works. Note that the case of *typename* and
185 the name of the type in your query must match!
186
187
188.. function:: register_adapter(type, callable)
189
190 Registers a callable to convert the custom Python type *type* into one of
191 SQLite's supported types. The callable *callable* accepts as single parameter
192 the Python value, and must return a value of the following types: int, long,
193 float, str (UTF-8 encoded), unicode or buffer.
194
195
196.. function:: complete_statement(sql)
197
198 Returns :const:`True` if the string *sql* contains one or more complete SQL
199 statements terminated by semicolons. It does not verify that the SQL is
200 syntactically correct, only that there are no unclosed string literals and the
201 statement is terminated by a semicolon.
202
203 This can be used to build a shell for SQLite, as in the following example:
204
205
206 .. literalinclude:: ../includes/sqlite3/complete_statement.py
207
208
209.. function:: enable_callback_tracebacks(flag)
210
211 By default you will not get any tracebacks in user-defined functions,
212 aggregates, converters, authorizer callbacks etc. If you want to debug them, you
213 can call this function with *flag* as True. Afterwards, you will get tracebacks
214 from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature
215 again.
216
217
218.. _sqlite3-connection-objects:
219
220Connection Objects
221------------------
222
Georg Brandl26497d92008-10-08 17:20:20 +0000223.. class:: Connection
224
225 A SQLite database connection has the following attributes and methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000226
227.. attribute:: Connection.isolation_level
228
Benjamin Peterson78f98a42008-11-26 17:39:17 +0000229 Get or set the current isolation level. :const:`None` for autocommit mode or
230 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
Georg Brandl8ec7f652007-08-15 14:28:01 +0000231 :ref:`sqlite3-controlling-transactions` for a more detailed explanation.
232
233
234.. method:: Connection.cursor([cursorClass])
235
236 The cursor method accepts a single optional parameter *cursorClass*. If
237 supplied, this must be a custom cursor class that extends
238 :class:`sqlite3.Cursor`.
239
240
Gerhard Häring41309302008-03-29 01:27:37 +0000241.. method:: Connection.commit()
242
243 This method commits the current transaction. If you don't call this method,
Ezio Melotti1e87da12011-10-19 10:39:35 +0300244 anything you did since the last call to ``commit()`` is not visible from
Gerhard Häring41309302008-03-29 01:27:37 +0000245 other database connections. If you wonder why you don't see the data you've
246 written to the database, please check you didn't forget to call this method.
247
248.. method:: Connection.rollback()
249
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000250 This method rolls back any changes to the database since the last call to
Gerhard Häring41309302008-03-29 01:27:37 +0000251 :meth:`commit`.
252
253.. method:: Connection.close()
254
255 This closes the database connection. Note that this does not automatically
256 call :meth:`commit`. If you just close your database connection without
257 calling :meth:`commit` first, your changes will be lost!
258
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259.. method:: Connection.execute(sql, [parameters])
260
261 This is a nonstandard shortcut that creates an intermediate cursor object by
Georg Brandl26946ec2010-11-26 07:42:15 +0000262 calling the cursor method, then calls the cursor's :meth:`execute
263 <Cursor.execute>` method with the parameters given.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000264
265
266.. method:: Connection.executemany(sql, [parameters])
267
268 This is a nonstandard shortcut that creates an intermediate cursor object by
Georg Brandl26946ec2010-11-26 07:42:15 +0000269 calling the cursor method, then calls the cursor's :meth:`executemany
270 <Cursor.executemany>` method with the parameters given.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000271
Georg Brandl8ec7f652007-08-15 14:28:01 +0000272.. method:: Connection.executescript(sql_script)
273
274 This is a nonstandard shortcut that creates an intermediate cursor object by
Georg Brandl26946ec2010-11-26 07:42:15 +0000275 calling the cursor method, then calls the cursor's :meth:`executescript
276 <Cursor.executescript>` method with the parameters given.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277
278
279.. method:: Connection.create_function(name, num_params, func)
280
281 Creates a user-defined function that you can later use from within SQL
282 statements under the function name *name*. *num_params* is the number of
283 parameters the function accepts, and *func* is a Python callable that is called
284 as the SQL function.
285
286 The function can return any of the types supported by SQLite: unicode, str, int,
287 long, float, buffer and None.
288
289 Example:
290
291 .. literalinclude:: ../includes/sqlite3/md5func.py
292
293
294.. method:: Connection.create_aggregate(name, num_params, aggregate_class)
295
296 Creates a user-defined aggregate function.
297
298 The aggregate class must implement a ``step`` method, which accepts the number
299 of parameters *num_params*, and a ``finalize`` method which will return the
300 final result of the aggregate.
301
302 The ``finalize`` method can return any of the types supported by SQLite:
303 unicode, str, int, long, float, buffer and None.
304
305 Example:
306
307 .. literalinclude:: ../includes/sqlite3/mysumaggr.py
308
309
310.. method:: Connection.create_collation(name, callable)
311
312 Creates a collation with the specified *name* and *callable*. The callable will
313 be passed two string arguments. It should return -1 if the first is ordered
314 lower than the second, 0 if they are ordered equal and 1 if the first is ordered
315 higher than the second. Note that this controls sorting (ORDER BY in SQL) so
316 your comparisons don't affect other SQL operations.
317
318 Note that the callable will get its parameters as Python bytestrings, which will
319 normally be encoded in UTF-8.
320
321 The following example shows a custom collation that sorts "the wrong way":
322
323 .. literalinclude:: ../includes/sqlite3/collation_reverse.py
324
325 To remove a collation, call ``create_collation`` with None as callable::
326
327 con.create_collation("reverse", None)
328
329
330.. method:: Connection.interrupt()
331
332 You can call this method from a different thread to abort any queries that might
333 be executing on the connection. The query will then abort and the caller will
334 get an exception.
335
336
337.. method:: Connection.set_authorizer(authorizer_callback)
338
339 This routine registers a callback. The callback is invoked for each attempt to
340 access a column of a table in the database. The callback should return
341 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
342 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
343 column should be treated as a NULL value. These constants are available in the
344 :mod:`sqlite3` module.
345
346 The first argument to the callback signifies what kind of operation is to be
347 authorized. The second and third argument will be arguments or :const:`None`
348 depending on the first argument. The 4th argument is the name of the database
349 ("main", "temp", etc.) if applicable. The 5th argument is the name of the
350 inner-most trigger or view that is responsible for the access attempt or
351 :const:`None` if this access attempt is directly from input SQL code.
352
353 Please consult the SQLite documentation about the possible values for the first
354 argument and the meaning of the second and third argument depending on the first
355 one. All necessary constants are available in the :mod:`sqlite3` module.
356
357
Gerhard Häring41309302008-03-29 01:27:37 +0000358.. method:: Connection.set_progress_handler(handler, n)
359
360 .. versionadded:: 2.6
361
362 This routine registers a callback. The callback is invoked for every *n*
363 instructions of the SQLite virtual machine. This is useful if you want to
364 get called from SQLite during long-running operations, for example to update
365 a GUI.
366
367 If you want to clear any previously installed progress handler, call the
368 method with :const:`None` for *handler*.
369
370
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000371.. method:: Connection.enable_load_extension(enabled)
372
373 .. versionadded:: 2.7
374
375 This routine allows/disallows the SQLite engine to load SQLite extensions
376 from shared libraries. SQLite extensions can define new functions,
Georg Brandl26946ec2010-11-26 07:42:15 +0000377 aggregates or whole new virtual table implementations. One well-known
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000378 extension is the fulltext-search extension distributed with SQLite.
379
380 .. literalinclude:: ../includes/sqlite3/load_extension.py
381
Senthil Kumaran7bf5ba02011-06-25 20:48:21 -0700382 Loadable extensions are disabled by default. See [#f1]_
383
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000384.. method:: Connection.load_extension(path)
385
386 .. versionadded:: 2.7
387
Georg Brandl26946ec2010-11-26 07:42:15 +0000388 This routine loads a SQLite extension from a shared library. You have to
389 enable extension loading with :meth:`enable_load_extension` before you can
390 use this routine.
Gerhard Häring3bbb6722010-03-05 09:12:37 +0000391
Senthil Kumaran7bf5ba02011-06-25 20:48:21 -0700392 Loadable extensions are disabled by default. See [#f1]_
393
Georg Brandl8ec7f652007-08-15 14:28:01 +0000394.. attribute:: Connection.row_factory
395
396 You can change this attribute to a callable that accepts the cursor and the
397 original row as a tuple and will return the real result row. This way, you can
398 implement more advanced ways of returning results, such as returning an object
399 that can also access columns by name.
400
401 Example:
402
403 .. literalinclude:: ../includes/sqlite3/row_factory.py
404
405 If returning a tuple doesn't suffice and you want name-based access to
406 columns, you should consider setting :attr:`row_factory` to the
407 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
408 index-based and case-insensitive name-based access to columns with almost no
409 memory overhead. It will probably be better than your own custom
410 dictionary-based approach or even a db_row based solution.
411
Georg Brandlb19be572007-12-29 10:57:00 +0000412 .. XXX what's a db_row-based solution?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000413
414
415.. attribute:: Connection.text_factory
416
Georg Brandl26497d92008-10-08 17:20:20 +0000417 Using this attribute you can control what objects are returned for the ``TEXT``
418 data type. By default, this attribute is set to :class:`unicode` and the
419 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000420 return bytestrings instead, you can set it to :class:`str`.
421
422 For efficiency reasons, there's also a way to return Unicode objects only for
423 non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to
424 :const:`sqlite3.OptimizedUnicode`.
425
426 You can also set it to any other callable that accepts a single bytestring
427 parameter and returns the resulting object.
428
429 See the following example code for illustration:
430
431 .. literalinclude:: ../includes/sqlite3/text_factory.py
432
433
434.. attribute:: Connection.total_changes
435
436 Returns the total number of database rows that have been modified, inserted, or
437 deleted since the database connection was opened.
438
439
Gregory P. Smithb9803422008-03-28 08:32:09 +0000440.. attribute:: Connection.iterdump
441
442 Returns an iterator to dump the database in an SQL text format. Useful when
443 saving an in-memory database for later restoration. This function provides
444 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
445 shell.
446
447 .. versionadded:: 2.6
448
449 Example::
450
451 # Convert file existing_db.db to SQL dump file dump.sql
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000452 import sqlite3, os
Gregory P. Smithb9803422008-03-28 08:32:09 +0000453
454 con = sqlite3.connect('existing_db.db')
Georg Brandlb9bfea72008-11-06 10:19:11 +0000455 with open('dump.sql', 'w') as f:
456 for line in con.iterdump():
457 f.write('%s\n' % line)
Gregory P. Smithb9803422008-03-28 08:32:09 +0000458
459
Georg Brandl8ec7f652007-08-15 14:28:01 +0000460.. _sqlite3-cursor-objects:
461
462Cursor Objects
463--------------
464
Georg Brandl26946ec2010-11-26 07:42:15 +0000465.. class:: Cursor
Georg Brandl8ec7f652007-08-15 14:28:01 +0000466
Georg Brandl26946ec2010-11-26 07:42:15 +0000467 A :class:`Cursor` instance has the following attributes and methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000468
469.. method:: Cursor.execute(sql, [parameters])
470
Georg Brandlf558d2e2008-01-19 20:53:07 +0000471 Executes an SQL statement. The SQL statement may be parametrized (i. e.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000472 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
473 kinds of placeholders: question marks (qmark style) and named placeholders
474 (named style).
475
476 This example shows how to use parameters with qmark style:
477
478 .. literalinclude:: ../includes/sqlite3/execute_1.py
479
480 This example shows how to use the named style:
481
482 .. literalinclude:: ../includes/sqlite3/execute_2.py
483
484 :meth:`execute` will only execute a single SQL statement. If you try to execute
485 more than one statement with it, it will raise a Warning. Use
486 :meth:`executescript` if you want to execute multiple SQL statements with one
487 call.
488
489
490.. method:: Cursor.executemany(sql, seq_of_parameters)
491
Georg Brandlf558d2e2008-01-19 20:53:07 +0000492 Executes an SQL command against all parameter sequences or mappings found in
Georg Brandle7a09902007-10-21 12:10:28 +0000493 the sequence *sql*. The :mod:`sqlite3` module also allows using an
494 :term:`iterator` yielding parameters instead of a sequence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000495
496 .. literalinclude:: ../includes/sqlite3/executemany_1.py
497
Georg Brandlcf3fb252007-10-21 10:52:38 +0000498 Here's a shorter example using a :term:`generator`:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000499
500 .. literalinclude:: ../includes/sqlite3/executemany_2.py
501
502
503.. method:: Cursor.executescript(sql_script)
504
505 This is a nonstandard convenience method for executing multiple SQL statements
Georg Brandl26497d92008-10-08 17:20:20 +0000506 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
Georg Brandl8ec7f652007-08-15 14:28:01 +0000507 gets as a parameter.
508
509 *sql_script* can be a bytestring or a Unicode string.
510
511 Example:
512
513 .. literalinclude:: ../includes/sqlite3/executescript.py
514
515
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000516.. method:: Cursor.fetchone()
517
Georg Brandlf558d2e2008-01-19 20:53:07 +0000518 Fetches the next row of a query result set, returning a single sequence,
Georg Brandl26497d92008-10-08 17:20:20 +0000519 or :const:`None` when no more data is available.
Georg Brandlf558d2e2008-01-19 20:53:07 +0000520
521
522.. method:: Cursor.fetchmany([size=cursor.arraysize])
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000523
Georg Brandlf558d2e2008-01-19 20:53:07 +0000524 Fetches the next set of rows of a query result, returning a list. An empty
525 list is returned when no more rows are available.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000526
Georg Brandlf558d2e2008-01-19 20:53:07 +0000527 The number of rows to fetch per call is specified by the *size* parameter.
528 If it is not given, the cursor's arraysize determines the number of rows
529 to be fetched. The method should try to fetch as many rows as indicated by
530 the size parameter. If this is not possible due to the specified number of
531 rows not being available, fewer rows may be returned.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000532
Georg Brandlf558d2e2008-01-19 20:53:07 +0000533 Note there are performance considerations involved with the *size* parameter.
534 For optimal performance, it is usually best to use the arraysize attribute.
535 If the *size* parameter is used, then it is best for it to retain the same
536 value from one :meth:`fetchmany` call to the next.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000537
538.. method:: Cursor.fetchall()
Georg Brandlf558d2e2008-01-19 20:53:07 +0000539
540 Fetches all (remaining) rows of a query result, returning a list. Note that
541 the cursor's arraysize attribute can affect the performance of this operation.
542 An empty list is returned when no rows are available.
543
544
Georg Brandl8ec7f652007-08-15 14:28:01 +0000545.. attribute:: Cursor.rowcount
546
547 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
548 attribute, the database engine's own support for the determination of "rows
549 affected"/"rows selected" is quirky.
550
Georg Brandl8ec7f652007-08-15 14:28:01 +0000551 For ``DELETE`` statements, SQLite reports :attr:`rowcount` as 0 if you make a
552 ``DELETE FROM table`` without any condition.
553
554 For :meth:`executemany` statements, the number of modifications are summed up
555 into :attr:`rowcount`.
556
557 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
Georg Brandl26497d92008-10-08 17:20:20 +0000558 case no ``executeXX()`` has been performed on the cursor or the rowcount of the
559 last operation is not determinable by the interface".
Georg Brandl8ec7f652007-08-15 14:28:01 +0000560
Georg Brandl891f1d32007-08-23 20:40:01 +0000561 This includes ``SELECT`` statements because we cannot determine the number of
562 rows a query produced until all rows were fetched.
563
Gerhard Häringc15317e2008-03-29 19:11:52 +0000564.. attribute:: Cursor.lastrowid
565
566 This read-only attribute provides the rowid of the last modified row. It is
567 only set if you issued a ``INSERT`` statement using the :meth:`execute`
568 method. For operations other than ``INSERT`` or when :meth:`executemany` is
569 called, :attr:`lastrowid` is set to :const:`None`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000570
Georg Brandl26497d92008-10-08 17:20:20 +0000571.. attribute:: Cursor.description
572
573 This read-only attribute provides the column names of the last query. To
574 remain compatible with the Python DB API, it returns a 7-tuple for each
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000575 column where the last six items of each tuple are :const:`None`.
576
Georg Brandl26497d92008-10-08 17:20:20 +0000577 It is set for ``SELECT`` statements without any matching rows as well.
578
579.. _sqlite3-row-objects:
580
581Row Objects
582-----------
583
584.. class:: Row
585
586 A :class:`Row` instance serves as a highly optimized
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000587 :attr:`~Connection.row_factory` for :class:`Connection` objects.
Georg Brandl26497d92008-10-08 17:20:20 +0000588 It tries to mimic a tuple in most of its features.
589
590 It supports mapping access by column name and index, iteration,
591 representation, equality testing and :func:`len`.
592
593 If two :class:`Row` objects have exactly the same columns and their
594 members are equal, they compare equal.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000595
Georg Brandl26497d92008-10-08 17:20:20 +0000596 .. versionchanged:: 2.6
597 Added iteration and equality (hashability).
598
599 .. method:: keys
600
601 This method returns a tuple of column names. Immediately after a query,
602 it is the first member of each tuple in :attr:`Cursor.description`.
603
604 .. versionadded:: 2.6
605
606Let's assume we initialize a table as in the example given above::
607
Senthil Kumarane04d2562011-07-03 10:12:59 -0700608 conn = sqlite3.connect(":memory:")
609 c = conn.cursor()
610 c.execute('''create table stocks
611 (date text, trans text, symbol text,
612 qty real, price real)''')
613 c.execute("""insert into stocks
614 values ('2006-01-05','BUY','RHAT',100,35.14)""")
615 conn.commit()
616 c.close()
Georg Brandl26497d92008-10-08 17:20:20 +0000617
618Now we plug :class:`Row` in::
619
Senthil Kumarane04d2562011-07-03 10:12:59 -0700620 >>> conn.row_factory = sqlite3.Row
621 >>> c = conn.cursor()
622 >>> c.execute('select * from stocks')
623 <sqlite3.Cursor object at 0x7f4e7dd8fa80>
624 >>> r = c.fetchone()
625 >>> type(r)
626 <type 'sqlite3.Row'>
627 >>> r
628 (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
629 >>> len(r)
630 5
631 >>> r[2]
632 u'RHAT'
633 >>> r.keys()
634 ['date', 'trans', 'symbol', 'qty', 'price']
635 >>> r['qty']
636 100.0
637 >>> for member in r: print member
638 ...
639 2006-01-05
640 BUY
641 RHAT
642 100.0
643 35.14
Georg Brandl26497d92008-10-08 17:20:20 +0000644
645
Georg Brandl8ec7f652007-08-15 14:28:01 +0000646.. _sqlite3-types:
647
648SQLite and Python types
649-----------------------
650
651
652Introduction
653^^^^^^^^^^^^
654
Georg Brandl26497d92008-10-08 17:20:20 +0000655SQLite natively supports the following types: ``NULL``, ``INTEGER``,
656``REAL``, ``TEXT``, ``BLOB``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000657
658The following Python types can thus be sent to SQLite without any problem:
659
Georg Brandl26497d92008-10-08 17:20:20 +0000660+-----------------------------+-------------+
661| Python type | SQLite type |
662+=============================+=============+
663| :const:`None` | ``NULL`` |
664+-----------------------------+-------------+
665| :class:`int` | ``INTEGER`` |
666+-----------------------------+-------------+
667| :class:`long` | ``INTEGER`` |
668+-----------------------------+-------------+
669| :class:`float` | ``REAL`` |
670+-----------------------------+-------------+
671| :class:`str` (UTF8-encoded) | ``TEXT`` |
672+-----------------------------+-------------+
673| :class:`unicode` | ``TEXT`` |
674+-----------------------------+-------------+
675| :class:`buffer` | ``BLOB`` |
676+-----------------------------+-------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000677
678This is how SQLite types are converted to Python types by default:
679
Georg Brandl26497d92008-10-08 17:20:20 +0000680+-------------+----------------------------------------------+
681| SQLite type | Python type |
682+=============+==============================================+
683| ``NULL`` | :const:`None` |
684+-------------+----------------------------------------------+
685| ``INTEGER`` | :class:`int` or :class:`long`, |
686| | depending on size |
687+-------------+----------------------------------------------+
688| ``REAL`` | :class:`float` |
689+-------------+----------------------------------------------+
690| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
691| | :class:`unicode` by default |
692+-------------+----------------------------------------------+
693| ``BLOB`` | :class:`buffer` |
694+-------------+----------------------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000695
696The type system of the :mod:`sqlite3` module is extensible in two ways: you can
697store additional Python types in a SQLite database via object adaptation, and
698you can let the :mod:`sqlite3` module convert SQLite types to different Python
699types via converters.
700
701
702Using adapters to store additional Python types in SQLite databases
703^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
704
705As described before, SQLite supports only a limited set of types natively. To
706use other Python types with SQLite, you must **adapt** them to one of the
707sqlite3 module's supported types for SQLite: one of NoneType, int, long, float,
708str, unicode, buffer.
709
710The :mod:`sqlite3` module uses Python object adaptation, as described in
711:pep:`246` for this. The protocol to use is :class:`PrepareProtocol`.
712
713There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
714type to one of the supported ones.
715
716
717Letting your object adapt itself
718""""""""""""""""""""""""""""""""
719
720This is a good approach if you write the class yourself. Let's suppose you have
721a class like this::
722
723 class Point(object):
724 def __init__(self, x, y):
725 self.x, self.y = x, y
726
727Now you want to store the point in a single SQLite column. First you'll have to
728choose one of the supported types first to be used for representing the point.
729Let's just use str and separate the coordinates using a semicolon. Then you need
730to give your class a method ``__conform__(self, protocol)`` which must return
731the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
732
733.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
734
735
736Registering an adapter callable
737"""""""""""""""""""""""""""""""
738
739The other possibility is to create a function that converts the type to the
740string representation and register the function with :meth:`register_adapter`.
741
742.. note::
743
Georg Brandla7395032007-10-21 12:15:05 +0000744 The type/class to adapt must be a :term:`new-style class`, i. e. it must have
Georg Brandl8ec7f652007-08-15 14:28:01 +0000745 :class:`object` as one of its bases.
746
747.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
748
749The :mod:`sqlite3` module has two default adapters for Python's built-in
750:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
751we want to store :class:`datetime.datetime` objects not in ISO representation,
752but as a Unix timestamp.
753
754.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
755
756
757Converting SQLite values to custom Python types
758^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
759
760Writing an adapter lets you send custom Python types to SQLite. But to make it
761really useful we need to make the Python to SQLite to Python roundtrip work.
762
763Enter converters.
764
765Let's go back to the :class:`Point` class. We stored the x and y coordinates
766separated via semicolons as strings in SQLite.
767
768First, we'll define a converter function that accepts the string as a parameter
769and constructs a :class:`Point` object from it.
770
771.. note::
772
773 Converter functions **always** get called with a string, no matter under which
774 data type you sent the value to SQLite.
775
Georg Brandl8ec7f652007-08-15 14:28:01 +0000776::
777
778 def convert_point(s):
779 x, y = map(float, s.split(";"))
780 return Point(x, y)
781
782Now you need to make the :mod:`sqlite3` module know that what you select from
783the database is actually a point. There are two ways of doing this:
784
785* Implicitly via the declared type
786
787* Explicitly via the column name
788
789Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
790for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
791
792The following example illustrates both approaches.
793
794.. literalinclude:: ../includes/sqlite3/converter_point.py
795
796
797Default adapters and converters
798^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
799
800There are default adapters for the date and datetime types in the datetime
801module. They will be sent as ISO dates/ISO timestamps to SQLite.
802
803The default converters are registered under the name "date" for
804:class:`datetime.date` and under the name "timestamp" for
805:class:`datetime.datetime`.
806
807This way, you can use date/timestamps from Python without any additional
808fiddling in most cases. The format of the adapters is also compatible with the
809experimental SQLite date/time functions.
810
811The following example demonstrates this.
812
813.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py
814
815
816.. _sqlite3-controlling-transactions:
817
818Controlling Transactions
819------------------------
820
821By default, the :mod:`sqlite3` module opens transactions implicitly before a
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000822Data Modification Language (DML) statement (i.e.
Georg Brandl26497d92008-10-08 17:20:20 +0000823``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
824implicitly before a non-DML, non-query statement (i. e.
825anything other than ``SELECT`` or the aforementioned).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000826
827So if you are within a transaction and issue a command like ``CREATE TABLE
828...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
829before executing that command. There are two reasons for doing that. The first
830is that some of these commands don't work within transactions. The other reason
Georg Brandl498a9b32009-05-20 18:31:14 +0000831is that sqlite3 needs to keep track of the transaction state (if a transaction
Georg Brandl8ec7f652007-08-15 14:28:01 +0000832is active or not).
833
Georg Brandl498a9b32009-05-20 18:31:14 +0000834You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000835(or none at all) via the *isolation_level* parameter to the :func:`connect`
836call, or via the :attr:`isolation_level` property of connections.
837
838If you want **autocommit mode**, then set :attr:`isolation_level` to None.
839
840Otherwise leave it at its default, which will result in a plain "BEGIN"
Georg Brandlb9bfea72008-11-06 10:19:11 +0000841statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
842"IMMEDIATE" or "EXCLUSIVE".
Georg Brandl8ec7f652007-08-15 14:28:01 +0000843
Georg Brandl8ec7f652007-08-15 14:28:01 +0000844
845
Georg Brandl498a9b32009-05-20 18:31:14 +0000846Using :mod:`sqlite3` efficiently
847--------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000848
849
850Using shortcut methods
851^^^^^^^^^^^^^^^^^^^^^^
852
853Using the nonstandard :meth:`execute`, :meth:`executemany` and
854:meth:`executescript` methods of the :class:`Connection` object, your code can
855be written more concisely because you don't have to create the (often
856superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
857objects are created implicitly and these shortcut methods return the cursor
Georg Brandl26497d92008-10-08 17:20:20 +0000858objects. This way, you can execute a ``SELECT`` statement and iterate over it
Georg Brandl8ec7f652007-08-15 14:28:01 +0000859directly using only a single call on the :class:`Connection` object.
860
861.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
862
863
864Accessing columns by name instead of by index
865^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
866
Georg Brandld7d4fd72009-07-26 14:37:28 +0000867One useful feature of the :mod:`sqlite3` module is the built-in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000868:class:`sqlite3.Row` class designed to be used as a row factory.
869
870Rows wrapped with this class can be accessed both by index (like tuples) and
871case-insensitively by name:
872
873.. literalinclude:: ../includes/sqlite3/rowclass.py
874
Gerhard Häring41309302008-03-29 01:27:37 +0000875
876Using the connection as a context manager
877^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
878
879.. versionadded:: 2.6
880
881Connection 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äring5f5c15f2010-08-06 06:14:12 +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.
Senthil Kumaran7bf5ba02011-06-25 20:48:21 -0700901
902.. rubric:: Footnotes
903
904.. [#f1] The sqlite3 module is not built with loadable extension support by
Senthil Kumarane04d2562011-07-03 10:12:59 -0700905 default, because some platforms (notably Mac OS X) have SQLite libraries
906 which are compiled without this feature. To get loadable extension support,
907 you must modify setup.py and remove the line that sets
908 SQLITE_OMIT_LOAD_EXTENSION.
Senthil Kumaran7bf5ba02011-06-25 20:48:21 -0700909