1: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 7.. sectionauthor:: Gerhard Häring <gh@ghaering.de> 8 9**Source code:** :source:`Lib/sqlite3/` 10 11-------------- 12 13SQLite is a C library that provides a lightweight disk-based database that 14doesn't require a separate server process and allows accessing the database 15using a nonstandard variant of the SQL query language. Some applications can use 16SQLite for internal data storage. It's also possible to prototype an 17application using SQLite and then port the code to a larger database such as 18PostgreSQL or Oracle. 19 20The sqlite3 module was written by Gerhard Häring. It provides a SQL interface 21compliant with the DB-API 2.0 specification described by :pep:`249`, and 22requires SQLite 3.7.15 or newer. 23 24To use the module, start by creating a :class:`Connection` object that 25represents the database. Here the data will be stored in the 26:file:`example.db` file:: 27 28 import sqlite3 29 con = sqlite3.connect('example.db') 30 31The special path name ``:memory:`` can be provided to create a temporary 32database in RAM. 33 34Once a :class:`Connection` has been established, create a :class:`Cursor` object 35and call its :meth:`~Cursor.execute` method to perform SQL commands:: 36 37 cur = con.cursor() 38 39 # Create table 40 cur.execute('''CREATE TABLE stocks 41 (date text, trans text, symbol text, qty real, price real)''') 42 43 # Insert a row of data 44 cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)") 45 46 # Save (commit) the changes 47 con.commit() 48 49 # We can also close the connection if we are done with it. 50 # Just be sure any changes have been committed or they will be lost. 51 con.close() 52 53The saved data is persistent: it can be reloaded in a subsequent session even 54after restarting the Python interpreter:: 55 56 import sqlite3 57 con = sqlite3.connect('example.db') 58 cur = con.cursor() 59 60To retrieve data after executing a SELECT statement, either treat the cursor as 61an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to 62retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list 63of the matching rows. 64 65This example uses the iterator form:: 66 67 >>> for row in cur.execute('SELECT * FROM stocks ORDER BY price'): 68 print(row) 69 70 ('2006-01-05', 'BUY', 'RHAT', 100, 35.14) 71 ('2006-03-28', 'BUY', 'IBM', 1000, 45.0) 72 ('2006-04-06', 'SELL', 'IBM', 500, 53.0) 73 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0) 74 75 76.. _sqlite3-placeholders: 77 78SQL operations usually need to use values from Python variables. However, 79beware of using Python's string operations to assemble queries, as they 80are vulnerable to SQL injection attacks (see the `xkcd webcomic 81<https://xkcd.com/327/>`_ for a humorous example of what can go wrong):: 82 83 # Never do this -- insecure! 84 symbol = 'RHAT' 85 cur.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol) 86 87Instead, use the DB-API's parameter substitution. To insert a variable into a 88query string, use a placeholder in the string, and substitute the actual values 89into the query by providing them as a :class:`tuple` of values to the second 90argument of the cursor's :meth:`~Cursor.execute` method. An SQL statement may 91use one of two kinds of placeholders: question marks (qmark style) or named 92placeholders (named style). For the qmark style, ``parameters`` must be a 93:term:`sequence <sequence>`. For the named style, it can be either a 94:term:`sequence <sequence>` or :class:`dict` instance. The length of the 95:term:`sequence <sequence>` must match the number of placeholders, or a 96:exc:`ProgrammingError` is raised. If a :class:`dict` is given, it must contain 97keys for all named parameters. Any extra items are ignored. Here's an example of 98both styles: 99 100.. literalinclude:: ../includes/sqlite3/execute_1.py 101 102 103.. seealso:: 104 105 https://www.sqlite.org 106 The SQLite web page; the documentation describes the syntax and the 107 available data types for the supported SQL dialect. 108 109 https://www.w3schools.com/sql/ 110 Tutorial, reference and examples for learning SQL syntax. 111 112 :pep:`249` - Database API Specification 2.0 113 PEP written by Marc-André Lemburg. 114 115 116.. _sqlite3-module-contents: 117 118Module functions and constants 119------------------------------ 120 121 122.. data:: apilevel 123 124 String constant stating the supported DB-API level. Required by the DB-API. 125 Hard-coded to ``"2.0"``. 126 127.. data:: paramstyle 128 129 String constant stating the type of parameter marker formatting expected by 130 the :mod:`sqlite3` module. Required by the DB-API. Hard-coded to 131 ``"qmark"``. 132 133 .. note:: 134 135 The :mod:`sqlite3` module supports both ``qmark`` and ``numeric`` DB-API 136 parameter styles, because that is what the underlying SQLite library 137 supports. However, the DB-API does not allow multiple values for 138 the ``paramstyle`` attribute. 139 140.. data:: version 141 142 The version number of this module, as a string. This is not the version of 143 the SQLite library. 144 145 146.. data:: version_info 147 148 The version number of this module, as a tuple of integers. This is not the 149 version of the SQLite library. 150 151 152.. data:: sqlite_version 153 154 The version number of the run-time SQLite library, as a string. 155 156 157.. data:: sqlite_version_info 158 159 The version number of the run-time SQLite library, as a tuple of integers. 160 161 162.. data:: threadsafety 163 164 Integer constant required by the DB-API, stating the level of thread safety 165 the :mod:`sqlite3` module supports. Currently hard-coded to ``1``, meaning 166 *"Threads may share the module, but not connections."* However, this may not 167 always be true. You can check the underlying SQLite library's compile-time 168 threaded mode using the following query:: 169 170 import sqlite3 171 con = sqlite3.connect(":memory:") 172 con.execute(""" 173 select * from pragma_compile_options 174 where compile_options like 'THREADSAFE=%' 175 """).fetchall() 176 177 Note that the `SQLITE_THREADSAFE levels 178 <https://sqlite.org/compile.html#threadsafe>`_ do not match the DB-API 2.0 179 ``threadsafety`` levels. 180 181 182.. data:: PARSE_DECLTYPES 183 184 This constant is meant to be used with the *detect_types* parameter of the 185 :func:`connect` function. 186 187 Setting it makes the :mod:`sqlite3` module parse the declared type for each 188 column it returns. It will parse out the first word of the declared type, 189 i. e. for "integer primary key", it will parse out "integer", or for 190 "number(10)" it will parse out "number". Then for that column, it will look 191 into the converters dictionary and use the converter function registered for 192 that type there. 193 194 195.. data:: PARSE_COLNAMES 196 197 This constant is meant to be used with the *detect_types* parameter of the 198 :func:`connect` function. 199 200 Setting this makes the SQLite interface parse the column name for each column it 201 returns. It will look for a string formed [mytype] in there, and then decide 202 that 'mytype' is the type of the column. It will try to find an entry of 203 'mytype' in the converters dictionary and then use the converter function found 204 there to return the value. The column name found in :attr:`Cursor.description` 205 does not include the type, i. e. if you use something like 206 ``'as "Expiration date [datetime]"'`` in your SQL, then we will parse out 207 everything until the first ``'['`` for the column name and strip 208 the preceding space: the column name would simply be "Expiration date". 209 210 211.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri]) 212 213 Opens a connection to the SQLite database file *database*. By default returns a 214 :class:`Connection` object, unless a custom *factory* is given. 215 216 *database* is a :term:`path-like object` giving the pathname (absolute or 217 relative to the current working directory) of the database file to be opened. 218 You can use ``":memory:"`` to open a database connection to a database that 219 resides in RAM instead of on disk. 220 221 When a database is accessed by multiple connections, and one of the processes 222 modifies the database, the SQLite database is locked until that transaction is 223 committed. The *timeout* parameter specifies how long the connection should wait 224 for the lock to go away until raising an exception. The default for the timeout 225 parameter is 5.0 (five seconds). 226 227 For the *isolation_level* parameter, please see the 228 :attr:`~Connection.isolation_level` property of :class:`Connection` objects. 229 230 SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If 231 you want to use other types you must add support for them yourself. The 232 *detect_types* parameter and the using custom **converters** registered with the 233 module-level :func:`register_converter` function allow you to easily do that. 234 235 *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to 236 any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn 237 type detection on. Due to SQLite behaviour, types can't be detected for generated 238 fields (for example ``max(data)``), even when *detect_types* parameter is set. In 239 such case, the returned type is :class:`str`. 240 241 By default, *check_same_thread* is :const:`True` and only the creating thread may 242 use the connection. If set :const:`False`, the returned connection may be shared 243 across multiple threads. When using multiple threads with the same connection 244 writing operations should be serialized by the user to avoid data corruption. 245 246 By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the 247 connect call. You can, however, subclass the :class:`Connection` class and make 248 :func:`connect` use your class instead by providing your class for the *factory* 249 parameter. 250 251 Consult the section :ref:`sqlite3-types` of this manual for details. 252 253 The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing 254 overhead. If you want to explicitly set the number of statements that are cached 255 for the connection, you can set the *cached_statements* parameter. The currently 256 implemented default is to cache 100 statements. 257 258 If *uri* is true, *database* is interpreted as a URI. This allows you 259 to specify options. For example, to open a database in read-only mode 260 you can use:: 261 262 db = sqlite3.connect('file:path/to/database?mode=ro', uri=True) 263 264 More information about this feature, including a list of recognized options, can 265 be found in the `SQLite URI documentation <https://www.sqlite.org/uri.html>`_. 266 267 .. audit-event:: sqlite3.connect database sqlite3.connect 268 .. audit-event:: sqlite3.connect/handle connection_handle sqlite3.connect 269 270 .. versionchanged:: 3.4 271 Added the *uri* parameter. 272 273 .. versionchanged:: 3.7 274 *database* can now also be a :term:`path-like object`, not only a string. 275 276 .. versionchanged:: 3.10 277 Added the ``sqlite3.connect/handle`` auditing event. 278 279 280.. function:: register_converter(typename, callable) 281 282 Registers a callable to convert a bytestring from the database into a custom 283 Python type. The callable will be invoked for all database values that are of 284 the type *typename*. Confer the parameter *detect_types* of the :func:`connect` 285 function for how the type detection works. Note that *typename* and the name of 286 the type in your query are matched in case-insensitive manner. 287 288 289.. function:: register_adapter(type, callable) 290 291 Registers a callable to convert the custom Python type *type* into one of 292 SQLite's supported types. The callable *callable* accepts as single parameter 293 the Python value, and must return a value of the following types: int, 294 float, str or bytes. 295 296 297.. function:: complete_statement(sql) 298 299 Returns :const:`True` if the string *sql* contains one or more complete SQL 300 statements terminated by semicolons. It does not verify that the SQL is 301 syntactically correct, only that there are no unclosed string literals and the 302 statement is terminated by a semicolon. 303 304 This can be used to build a shell for SQLite, as in the following example: 305 306 307 .. literalinclude:: ../includes/sqlite3/complete_statement.py 308 309 310.. function:: enable_callback_tracebacks(flag) 311 312 By default you will not get any tracebacks in user-defined functions, 313 aggregates, converters, authorizer callbacks etc. If you want to debug them, 314 you can call this function with *flag* set to ``True``. Afterwards, you will 315 get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to 316 disable the feature again. 317 318 319.. _sqlite3-connection-objects: 320 321Connection Objects 322------------------ 323 324.. class:: Connection 325 326 A SQLite database connection has the following attributes and methods: 327 328 .. attribute:: isolation_level 329 330 Get or set the current default isolation level. :const:`None` for autocommit mode or 331 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section 332 :ref:`sqlite3-controlling-transactions` for a more detailed explanation. 333 334 .. attribute:: in_transaction 335 336 :const:`True` if a transaction is active (there are uncommitted changes), 337 :const:`False` otherwise. Read-only attribute. 338 339 .. versionadded:: 3.2 340 341 .. method:: cursor(factory=Cursor) 342 343 The cursor method accepts a single optional parameter *factory*. If 344 supplied, this must be a callable returning an instance of :class:`Cursor` 345 or its subclasses. 346 347 .. method:: commit() 348 349 This method commits the current transaction. If you don't call this method, 350 anything you did since the last call to ``commit()`` is not visible from 351 other database connections. If you wonder why you don't see the data you've 352 written to the database, please check you didn't forget to call this method. 353 354 .. method:: rollback() 355 356 This method rolls back any changes to the database since the last call to 357 :meth:`commit`. 358 359 .. method:: close() 360 361 This closes the database connection. Note that this does not automatically 362 call :meth:`commit`. If you just close your database connection without 363 calling :meth:`commit` first, your changes will be lost! 364 365 .. method:: execute(sql[, parameters]) 366 367 This is a nonstandard shortcut that creates a cursor object by calling 368 the :meth:`~Connection.cursor` method, calls the cursor's 369 :meth:`~Cursor.execute` method with the *parameters* given, and returns 370 the cursor. 371 372 .. method:: executemany(sql[, parameters]) 373 374 This is a nonstandard shortcut that creates a cursor object by 375 calling the :meth:`~Connection.cursor` method, calls the cursor's 376 :meth:`~Cursor.executemany` method with the *parameters* given, and 377 returns the cursor. 378 379 .. method:: executescript(sql_script) 380 381 This is a nonstandard shortcut that creates a cursor object by 382 calling the :meth:`~Connection.cursor` method, calls the cursor's 383 :meth:`~Cursor.executescript` method with the given *sql_script*, and 384 returns the cursor. 385 386 .. method:: create_function(name, num_params, func, *, deterministic=False) 387 388 Creates a user-defined function that you can later use from within SQL 389 statements under the function name *name*. *num_params* is the number of 390 parameters the function accepts (if *num_params* is -1, the function may 391 take any number of arguments), and *func* is a Python callable that is 392 called as the SQL function. If *deterministic* is true, the created function 393 is marked as `deterministic <https://sqlite.org/deterministic.html>`_, which 394 allows SQLite to perform additional optimizations. This flag is supported by 395 SQLite 3.8.3 or higher, :exc:`NotSupportedError` will be raised if used 396 with older versions. 397 398 The function can return any of the types supported by SQLite: bytes, str, int, 399 float and ``None``. 400 401 .. versionchanged:: 3.8 402 The *deterministic* parameter was added. 403 404 Example: 405 406 .. literalinclude:: ../includes/sqlite3/md5func.py 407 408 409 .. method:: create_aggregate(name, num_params, aggregate_class) 410 411 Creates a user-defined aggregate function. 412 413 The aggregate class must implement a ``step`` method, which accepts the number 414 of parameters *num_params* (if *num_params* is -1, the function may take 415 any number of arguments), and a ``finalize`` method which will return the 416 final result of the aggregate. 417 418 The ``finalize`` method can return any of the types supported by SQLite: 419 bytes, str, int, float and ``None``. 420 421 Example: 422 423 .. literalinclude:: ../includes/sqlite3/mysumaggr.py 424 425 426 .. method:: create_collation(name, callable) 427 428 Creates a collation with the specified *name* and *callable*. The callable will 429 be passed two string arguments. It should return -1 if the first is ordered 430 lower than the second, 0 if they are ordered equal and 1 if the first is ordered 431 higher than the second. Note that this controls sorting (ORDER BY in SQL) so 432 your comparisons don't affect other SQL operations. 433 434 Note that the callable will get its parameters as Python bytestrings, which will 435 normally be encoded in UTF-8. 436 437 The following example shows a custom collation that sorts "the wrong way": 438 439 .. literalinclude:: ../includes/sqlite3/collation_reverse.py 440 441 To remove a collation, call ``create_collation`` with ``None`` as callable:: 442 443 con.create_collation("reverse", None) 444 445 446 .. method:: interrupt() 447 448 You can call this method from a different thread to abort any queries that might 449 be executing on the connection. The query will then abort and the caller will 450 get an exception. 451 452 453 .. method:: set_authorizer(authorizer_callback) 454 455 This routine registers a callback. The callback is invoked for each attempt to 456 access a column of a table in the database. The callback should return 457 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL 458 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the 459 column should be treated as a NULL value. These constants are available in the 460 :mod:`sqlite3` module. 461 462 The first argument to the callback signifies what kind of operation is to be 463 authorized. The second and third argument will be arguments or :const:`None` 464 depending on the first argument. The 4th argument is the name of the database 465 ("main", "temp", etc.) if applicable. The 5th argument is the name of the 466 inner-most trigger or view that is responsible for the access attempt or 467 :const:`None` if this access attempt is directly from input SQL code. 468 469 Please consult the SQLite documentation about the possible values for the first 470 argument and the meaning of the second and third argument depending on the first 471 one. All necessary constants are available in the :mod:`sqlite3` module. 472 473 474 .. method:: set_progress_handler(handler, n) 475 476 This routine registers a callback. The callback is invoked for every *n* 477 instructions of the SQLite virtual machine. This is useful if you want to 478 get called from SQLite during long-running operations, for example to update 479 a GUI. 480 481 If you want to clear any previously installed progress handler, call the 482 method with :const:`None` for *handler*. 483 484 Returning a non-zero value from the handler function will terminate the 485 currently executing query and cause it to raise an :exc:`OperationalError` 486 exception. 487 488 489 .. method:: set_trace_callback(trace_callback) 490 491 Registers *trace_callback* to be called for each SQL statement that is 492 actually executed by the SQLite backend. 493 494 The only argument passed to the callback is the statement (as 495 :class:`str`) that is being executed. The return value of the callback is 496 ignored. Note that the backend does not only run statements passed to the 497 :meth:`Cursor.execute` methods. Other sources include the 498 :ref:`transaction management <sqlite3-controlling-transactions>` of the 499 sqlite3 module and the execution of triggers defined in the current 500 database. 501 502 Passing :const:`None` as *trace_callback* will disable the trace callback. 503 504 .. note:: 505 Exceptions raised in the trace callback are not propagated. As a 506 development and debugging aid, use 507 :meth:`~sqlite3.enable_callback_tracebacks` to enable printing 508 tracebacks from exceptions raised in the trace callback. 509 510 .. versionadded:: 3.3 511 512 513 .. method:: enable_load_extension(enabled) 514 515 This routine allows/disallows the SQLite engine to load SQLite extensions 516 from shared libraries. SQLite extensions can define new functions, 517 aggregates or whole new virtual table implementations. One well-known 518 extension is the fulltext-search extension distributed with SQLite. 519 520 Loadable extensions are disabled by default. See [#f1]_. 521 522 .. audit-event:: sqlite3.enable_load_extension connection,enabled sqlite3.enable_load_extension 523 524 .. versionadded:: 3.2 525 526 .. versionchanged:: 3.10 527 Added the ``sqlite3.enable_load_extension`` auditing event. 528 529 .. literalinclude:: ../includes/sqlite3/load_extension.py 530 531 .. method:: load_extension(path) 532 533 This routine loads a SQLite extension from a shared library. You have to 534 enable extension loading with :meth:`enable_load_extension` before you can 535 use this routine. 536 537 Loadable extensions are disabled by default. See [#f1]_. 538 539 .. audit-event:: sqlite3.load_extension connection,path sqlite3.load_extension 540 541 .. versionadded:: 3.2 542 543 .. versionchanged:: 3.10 544 Added the ``sqlite3.load_extension`` auditing event. 545 546 .. attribute:: row_factory 547 548 You can change this attribute to a callable that accepts the cursor and the 549 original row as a tuple and will return the real result row. This way, you can 550 implement more advanced ways of returning results, such as returning an object 551 that can also access columns by name. 552 553 Example: 554 555 .. literalinclude:: ../includes/sqlite3/row_factory.py 556 557 If returning a tuple doesn't suffice and you want name-based access to 558 columns, you should consider setting :attr:`row_factory` to the 559 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both 560 index-based and case-insensitive name-based access to columns with almost no 561 memory overhead. It will probably be better than your own custom 562 dictionary-based approach or even a db_row based solution. 563 564 .. XXX what's a db_row-based solution? 565 566 567 .. attribute:: text_factory 568 569 Using this attribute you can control what objects are returned for the ``TEXT`` 570 data type. By default, this attribute is set to :class:`str` and the 571 :mod:`sqlite3` module will return :class:`str` objects for ``TEXT``. 572 If you want to return :class:`bytes` instead, you can set it to :class:`bytes`. 573 574 You can also set it to any other callable that accepts a single bytestring 575 parameter and returns the resulting object. 576 577 See the following example code for illustration: 578 579 .. literalinclude:: ../includes/sqlite3/text_factory.py 580 581 582 .. attribute:: total_changes 583 584 Returns the total number of database rows that have been modified, inserted, or 585 deleted since the database connection was opened. 586 587 588 .. method:: iterdump 589 590 Returns an iterator to dump the database in an SQL text format. Useful when 591 saving an in-memory database for later restoration. This function provides 592 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3` 593 shell. 594 595 Example:: 596 597 # Convert file existing_db.db to SQL dump file dump.sql 598 import sqlite3 599 600 con = sqlite3.connect('existing_db.db') 601 with open('dump.sql', 'w') as f: 602 for line in con.iterdump(): 603 f.write('%s\n' % line) 604 con.close() 605 606 607 .. method:: backup(target, *, pages=-1, progress=None, name="main", sleep=0.250) 608 609 This method makes a backup of a SQLite database even while it's being accessed 610 by other clients, or concurrently by the same connection. The copy will be 611 written into the mandatory argument *target*, that must be another 612 :class:`Connection` instance. 613 614 By default, or when *pages* is either ``0`` or a negative integer, the entire 615 database is copied in a single step; otherwise the method performs a loop 616 copying up to *pages* pages at a time. 617 618 If *progress* is specified, it must either be ``None`` or a callable object that 619 will be executed at each iteration with three integer arguments, respectively 620 the *status* of the last iteration, the *remaining* number of pages still to be 621 copied and the *total* number of pages. 622 623 The *name* argument specifies the database name that will be copied: it must be 624 a string containing either ``"main"``, the default, to indicate the main 625 database, ``"temp"`` to indicate the temporary database or the name specified 626 after the ``AS`` keyword in an ``ATTACH DATABASE`` statement for an attached 627 database. 628 629 The *sleep* argument specifies the number of seconds to sleep by between 630 successive attempts to backup remaining pages, can be specified either as an 631 integer or a floating point value. 632 633 Example 1, copy an existing database into another:: 634 635 import sqlite3 636 637 def progress(status, remaining, total): 638 print(f'Copied {total-remaining} of {total} pages...') 639 640 con = sqlite3.connect('existing_db.db') 641 bck = sqlite3.connect('backup.db') 642 with bck: 643 con.backup(bck, pages=1, progress=progress) 644 bck.close() 645 con.close() 646 647 Example 2, copy an existing database into a transient copy:: 648 649 import sqlite3 650 651 source = sqlite3.connect('existing_db.db') 652 dest = sqlite3.connect(':memory:') 653 source.backup(dest) 654 655 .. versionadded:: 3.7 656 657 658.. _sqlite3-cursor-objects: 659 660Cursor Objects 661-------------- 662 663.. class:: Cursor 664 665 A :class:`Cursor` instance has the following attributes and methods. 666 667 .. index:: single: ? (question mark); in SQL statements 668 .. index:: single: : (colon); in SQL statements 669 670 .. method:: execute(sql[, parameters]) 671 672 Executes an SQL statement. Values may be bound to the statement using 673 :ref:`placeholders <sqlite3-placeholders>`. 674 675 :meth:`execute` will only execute a single SQL statement. If you try to execute 676 more than one statement with it, it will raise a :exc:`.Warning`. Use 677 :meth:`executescript` if you want to execute multiple SQL statements with one 678 call. 679 680 681 .. method:: executemany(sql, seq_of_parameters) 682 683 Executes a :ref:`parameterized <sqlite3-placeholders>` SQL command 684 against all parameter sequences or mappings found in the sequence 685 *seq_of_parameters*. The :mod:`sqlite3` module also allows using an 686 :term:`iterator` yielding parameters instead of a sequence. 687 688 .. literalinclude:: ../includes/sqlite3/executemany_1.py 689 690 Here's a shorter example using a :term:`generator`: 691 692 .. literalinclude:: ../includes/sqlite3/executemany_2.py 693 694 695 .. method:: executescript(sql_script) 696 697 This is a nonstandard convenience method for executing multiple SQL statements 698 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it 699 gets as a parameter. This method disregards :attr:`isolation_level`; any 700 transaction control must be added to *sql_script*. 701 702 *sql_script* can be an instance of :class:`str`. 703 704 Example: 705 706 .. literalinclude:: ../includes/sqlite3/executescript.py 707 708 709 .. method:: fetchone() 710 711 Fetches the next row of a query result set, returning a single sequence, 712 or :const:`None` when no more data is available. 713 714 715 .. method:: fetchmany(size=cursor.arraysize) 716 717 Fetches the next set of rows of a query result, returning a list. An empty 718 list is returned when no more rows are available. 719 720 The number of rows to fetch per call is specified by the *size* parameter. 721 If it is not given, the cursor's arraysize determines the number of rows 722 to be fetched. The method should try to fetch as many rows as indicated by 723 the size parameter. If this is not possible due to the specified number of 724 rows not being available, fewer rows may be returned. 725 726 Note there are performance considerations involved with the *size* parameter. 727 For optimal performance, it is usually best to use the arraysize attribute. 728 If the *size* parameter is used, then it is best for it to retain the same 729 value from one :meth:`fetchmany` call to the next. 730 731 .. method:: fetchall() 732 733 Fetches all (remaining) rows of a query result, returning a list. Note that 734 the cursor's arraysize attribute can affect the performance of this operation. 735 An empty list is returned when no rows are available. 736 737 .. method:: close() 738 739 Close the cursor now (rather than whenever ``__del__`` is called). 740 741 The cursor will be unusable from this point forward; a :exc:`ProgrammingError` 742 exception will be raised if any operation is attempted with the cursor. 743 744 .. method:: setinputsizes(sizes) 745 746 Required by the DB-API. Is a no-op in :mod:`sqlite3`. 747 748 .. method:: setoutputsize(size [, column]) 749 750 Required by the DB-API. Is a no-op in :mod:`sqlite3`. 751 752 .. attribute:: rowcount 753 754 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this 755 attribute, the database engine's own support for the determination of "rows 756 affected"/"rows selected" is quirky. 757 758 For :meth:`executemany` statements, the number of modifications are summed up 759 into :attr:`rowcount`. 760 761 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in 762 case no ``executeXX()`` has been performed on the cursor or the rowcount of the 763 last operation is not determinable by the interface". This includes ``SELECT`` 764 statements because we cannot determine the number of rows a query produced 765 until all rows were fetched. 766 767 .. attribute:: lastrowid 768 769 This read-only attribute provides the row id of the last inserted row. It 770 is only updated after successful ``INSERT`` or ``REPLACE`` statements 771 using the :meth:`execute` method. For other statements, after 772 :meth:`executemany` or :meth:`executescript`, or if the insertion failed, 773 the value of ``lastrowid`` is left unchanged. The initial value of 774 ``lastrowid`` is :const:`None`. 775 776 .. note:: 777 Inserts into ``WITHOUT ROWID`` tables are not recorded. 778 779 .. versionchanged:: 3.6 780 Added support for the ``REPLACE`` statement. 781 782 .. attribute:: arraysize 783 784 Read/write attribute that controls the number of rows returned by :meth:`fetchmany`. 785 The default value is 1 which means a single row would be fetched per call. 786 787 .. attribute:: description 788 789 This read-only attribute provides the column names of the last query. To 790 remain compatible with the Python DB API, it returns a 7-tuple for each 791 column where the last six items of each tuple are :const:`None`. 792 793 It is set for ``SELECT`` statements without any matching rows as well. 794 795 .. attribute:: connection 796 797 This read-only attribute provides the SQLite database :class:`Connection` 798 used by the :class:`Cursor` object. A :class:`Cursor` object created by 799 calling :meth:`con.cursor() <Connection.cursor>` will have a 800 :attr:`connection` attribute that refers to *con*:: 801 802 >>> con = sqlite3.connect(":memory:") 803 >>> cur = con.cursor() 804 >>> cur.connection == con 805 True 806 807.. _sqlite3-row-objects: 808 809Row Objects 810----------- 811 812.. class:: Row 813 814 A :class:`Row` instance serves as a highly optimized 815 :attr:`~Connection.row_factory` for :class:`Connection` objects. 816 It tries to mimic a tuple in most of its features. 817 818 It supports mapping access by column name and index, iteration, 819 representation, equality testing and :func:`len`. 820 821 If two :class:`Row` objects have exactly the same columns and their 822 members are equal, they compare equal. 823 824 .. method:: keys 825 826 This method returns a list of column names. Immediately after a query, 827 it is the first member of each tuple in :attr:`Cursor.description`. 828 829 .. versionchanged:: 3.5 830 Added support of slicing. 831 832Let's assume we initialize a table as in the example given above:: 833 834 con = sqlite3.connect(":memory:") 835 cur = con.cursor() 836 cur.execute('''create table stocks 837 (date text, trans text, symbol text, 838 qty real, price real)''') 839 cur.execute("""insert into stocks 840 values ('2006-01-05','BUY','RHAT',100,35.14)""") 841 con.commit() 842 cur.close() 843 844Now we plug :class:`Row` in:: 845 846 >>> con.row_factory = sqlite3.Row 847 >>> cur = con.cursor() 848 >>> cur.execute('select * from stocks') 849 <sqlite3.Cursor object at 0x7f4e7dd8fa80> 850 >>> r = cur.fetchone() 851 >>> type(r) 852 <class 'sqlite3.Row'> 853 >>> tuple(r) 854 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14) 855 >>> len(r) 856 5 857 >>> r[2] 858 'RHAT' 859 >>> r.keys() 860 ['date', 'trans', 'symbol', 'qty', 'price'] 861 >>> r['qty'] 862 100.0 863 >>> for member in r: 864 ... print(member) 865 ... 866 2006-01-05 867 BUY 868 RHAT 869 100.0 870 35.14 871 872 873.. _sqlite3-exceptions: 874 875Exceptions 876---------- 877 878.. exception:: Warning 879 880 A subclass of :exc:`Exception`. 881 882.. exception:: Error 883 884 The base class of the other exceptions in this module. It is a subclass 885 of :exc:`Exception`. 886 887.. exception:: DatabaseError 888 889 Exception raised for errors that are related to the database. 890 891.. exception:: IntegrityError 892 893 Exception raised when the relational integrity of the database is affected, 894 e.g. a foreign key check fails. It is a subclass of :exc:`DatabaseError`. 895 896.. exception:: ProgrammingError 897 898 Exception raised for programming errors, e.g. table not found or already 899 exists, syntax error in the SQL statement, wrong number of parameters 900 specified, etc. It is a subclass of :exc:`DatabaseError`. 901 902.. exception:: OperationalError 903 904 Exception raised for errors that are related to the database's operation 905 and not necessarily under the control of the programmer, e.g. an unexpected 906 disconnect occurs, the data source name is not found, a transaction could 907 not be processed, etc. It is a subclass of :exc:`DatabaseError`. 908 909.. exception:: NotSupportedError 910 911 Exception raised in case a method or database API was used which is not 912 supported by the database, e.g. calling the :meth:`~Connection.rollback` 913 method on a connection that does not support transaction or has 914 transactions turned off. It is a subclass of :exc:`DatabaseError`. 915 916 917.. _sqlite3-types: 918 919SQLite and Python types 920----------------------- 921 922 923Introduction 924^^^^^^^^^^^^ 925 926SQLite natively supports the following types: ``NULL``, ``INTEGER``, 927``REAL``, ``TEXT``, ``BLOB``. 928 929The following Python types can thus be sent to SQLite without any problem: 930 931+-------------------------------+-------------+ 932| Python type | SQLite type | 933+===============================+=============+ 934| :const:`None` | ``NULL`` | 935+-------------------------------+-------------+ 936| :class:`int` | ``INTEGER`` | 937+-------------------------------+-------------+ 938| :class:`float` | ``REAL`` | 939+-------------------------------+-------------+ 940| :class:`str` | ``TEXT`` | 941+-------------------------------+-------------+ 942| :class:`bytes` | ``BLOB`` | 943+-------------------------------+-------------+ 944 945 946This is how SQLite types are converted to Python types by default: 947 948+-------------+----------------------------------------------+ 949| SQLite type | Python type | 950+=============+==============================================+ 951| ``NULL`` | :const:`None` | 952+-------------+----------------------------------------------+ 953| ``INTEGER`` | :class:`int` | 954+-------------+----------------------------------------------+ 955| ``REAL`` | :class:`float` | 956+-------------+----------------------------------------------+ 957| ``TEXT`` | depends on :attr:`~Connection.text_factory`, | 958| | :class:`str` by default | 959+-------------+----------------------------------------------+ 960| ``BLOB`` | :class:`bytes` | 961+-------------+----------------------------------------------+ 962 963The type system of the :mod:`sqlite3` module is extensible in two ways: you can 964store additional Python types in a SQLite database via object adaptation, and 965you can let the :mod:`sqlite3` module convert SQLite types to different Python 966types via converters. 967 968 969Using adapters to store additional Python types in SQLite databases 970^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 971 972As described before, SQLite supports only a limited set of types natively. To 973use other Python types with SQLite, you must **adapt** them to one of the 974sqlite3 module's supported types for SQLite: one of NoneType, int, float, 975str, bytes. 976 977There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python 978type to one of the supported ones. 979 980 981Letting your object adapt itself 982"""""""""""""""""""""""""""""""" 983 984This is a good approach if you write the class yourself. Let's suppose you have 985a class like this:: 986 987 class Point: 988 def __init__(self, x, y): 989 self.x, self.y = x, y 990 991Now you want to store the point in a single SQLite column. First you'll have to 992choose one of the supported types to be used for representing the point. 993Let's just use str and separate the coordinates using a semicolon. Then you need 994to give your class a method ``__conform__(self, protocol)`` which must return 995the converted value. The parameter *protocol* will be :class:`PrepareProtocol`. 996 997.. literalinclude:: ../includes/sqlite3/adapter_point_1.py 998 999 1000Registering an adapter callable 1001""""""""""""""""""""""""""""""" 1002 1003The other possibility is to create a function that converts the type to the 1004string representation and register the function with :meth:`register_adapter`. 1005 1006.. literalinclude:: ../includes/sqlite3/adapter_point_2.py 1007 1008The :mod:`sqlite3` module has two default adapters for Python's built-in 1009:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose 1010we want to store :class:`datetime.datetime` objects not in ISO representation, 1011but as a Unix timestamp. 1012 1013.. literalinclude:: ../includes/sqlite3/adapter_datetime.py 1014 1015 1016Converting SQLite values to custom Python types 1017^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1018 1019Writing an adapter lets you send custom Python types to SQLite. But to make it 1020really useful we need to make the Python to SQLite to Python roundtrip work. 1021 1022Enter converters. 1023 1024Let's go back to the :class:`Point` class. We stored the x and y coordinates 1025separated via semicolons as strings in SQLite. 1026 1027First, we'll define a converter function that accepts the string as a parameter 1028and constructs a :class:`Point` object from it. 1029 1030.. note:: 1031 1032 Converter functions **always** get called with a :class:`bytes` object, no 1033 matter under which data type you sent the value to SQLite. 1034 1035:: 1036 1037 def convert_point(s): 1038 x, y = map(float, s.split(b";")) 1039 return Point(x, y) 1040 1041Now you need to make the :mod:`sqlite3` module know that what you select from 1042the database is actually a point. There are two ways of doing this: 1043 1044* Implicitly via the declared type 1045 1046* Explicitly via the column name 1047 1048Both ways are described in section :ref:`sqlite3-module-contents`, in the entries 1049for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`. 1050 1051The following example illustrates both approaches. 1052 1053.. literalinclude:: ../includes/sqlite3/converter_point.py 1054 1055 1056Default adapters and converters 1057^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1058 1059There are default adapters for the date and datetime types in the datetime 1060module. They will be sent as ISO dates/ISO timestamps to SQLite. 1061 1062The default converters are registered under the name "date" for 1063:class:`datetime.date` and under the name "timestamp" for 1064:class:`datetime.datetime`. 1065 1066This way, you can use date/timestamps from Python without any additional 1067fiddling in most cases. The format of the adapters is also compatible with the 1068experimental SQLite date/time functions. 1069 1070The following example demonstrates this. 1071 1072.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py 1073 1074If a timestamp stored in SQLite has a fractional part longer than 6 1075numbers, its value will be truncated to microsecond precision by the 1076timestamp converter. 1077 1078.. note:: 1079 1080 The default "timestamp" converter ignores UTC offsets in the database and 1081 always returns a naive :class:`datetime.datetime` object. To preserve UTC 1082 offsets in timestamps, either leave converters disabled, or register an 1083 offset-aware converter with :func:`register_converter`. 1084 1085.. _sqlite3-controlling-transactions: 1086 1087Controlling Transactions 1088------------------------ 1089 1090The underlying ``sqlite3`` library operates in ``autocommit`` mode by default, 1091but the Python :mod:`sqlite3` module by default does not. 1092 1093``autocommit`` mode means that statements that modify the database take effect 1094immediately. A ``BEGIN`` or ``SAVEPOINT`` statement disables ``autocommit`` 1095mode, and a ``COMMIT``, a ``ROLLBACK``, or a ``RELEASE`` that ends the 1096outermost transaction, turns ``autocommit`` mode back on. 1097 1098The Python :mod:`sqlite3` module by default issues a ``BEGIN`` statement 1099implicitly before a Data Modification Language (DML) statement (i.e. 1100``INSERT``/``UPDATE``/``DELETE``/``REPLACE``). 1101 1102You can control which kind of ``BEGIN`` statements :mod:`sqlite3` implicitly 1103executes via the *isolation_level* parameter to the :func:`connect` 1104call, or via the :attr:`isolation_level` property of connections. 1105If you specify no *isolation_level*, a plain ``BEGIN`` is used, which is 1106equivalent to specifying ``DEFERRED``. Other possible values are ``IMMEDIATE`` 1107and ``EXCLUSIVE``. 1108 1109You can disable the :mod:`sqlite3` module's implicit transaction management by 1110setting :attr:`isolation_level` to ``None``. This will leave the underlying 1111``sqlite3`` library operating in ``autocommit`` mode. You can then completely 1112control the transaction state by explicitly issuing ``BEGIN``, ``ROLLBACK``, 1113``SAVEPOINT``, and ``RELEASE`` statements in your code. 1114 1115Note that :meth:`~Cursor.executescript` disregards 1116:attr:`isolation_level`; any transaction control must be added explicitly. 1117 1118.. versionchanged:: 3.6 1119 :mod:`sqlite3` used to implicitly commit an open transaction before DDL 1120 statements. This is no longer the case. 1121 1122 1123Using :mod:`sqlite3` efficiently 1124-------------------------------- 1125 1126 1127Using shortcut methods 1128^^^^^^^^^^^^^^^^^^^^^^ 1129 1130Using the nonstandard :meth:`execute`, :meth:`executemany` and 1131:meth:`executescript` methods of the :class:`Connection` object, your code can 1132be written more concisely because you don't have to create the (often 1133superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor` 1134objects are created implicitly and these shortcut methods return the cursor 1135objects. This way, you can execute a ``SELECT`` statement and iterate over it 1136directly using only a single call on the :class:`Connection` object. 1137 1138.. literalinclude:: ../includes/sqlite3/shortcut_methods.py 1139 1140 1141Accessing columns by name instead of by index 1142^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1143 1144One useful feature of the :mod:`sqlite3` module is the built-in 1145:class:`sqlite3.Row` class designed to be used as a row factory. 1146 1147Rows wrapped with this class can be accessed both by index (like tuples) and 1148case-insensitively by name: 1149 1150.. literalinclude:: ../includes/sqlite3/rowclass.py 1151 1152 1153Using the connection as a context manager 1154^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1155 1156Connection objects can be used as context managers 1157that automatically commit or rollback transactions. In the event of an 1158exception, the transaction is rolled back; otherwise, the transaction is 1159committed: 1160 1161.. literalinclude:: ../includes/sqlite3/ctx_manager.py 1162 1163 1164.. rubric:: Footnotes 1165 1166.. [#f1] The sqlite3 module is not built with loadable extension support by 1167 default, because some platforms (notably macOS) have SQLite 1168 libraries which are compiled without this feature. To get loadable 1169 extension support, you must pass the 1170 :option:`--enable-loadable-sqlite-extensions` option to configure. 1171