summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fsqlite3.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/library%2Fsqlite3.html')
-rw-r--r--devdocs/python~3.12/library%2Fsqlite3.html862
1 files changed, 862 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Fsqlite3.html b/devdocs/python~3.12/library%2Fsqlite3.html
new file mode 100644
index 00000000..206757c4
--- /dev/null
+++ b/devdocs/python~3.12/library%2Fsqlite3.html
@@ -0,0 +1,862 @@
+ <span id="sqlite3-db-api-2-0-interface-for-sqlite-databases"></span><h1>sqlite3 — DB-API 2.0 interface for SQLite databases</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/sqlite3/">Lib/sqlite3/</a></p> <p id="sqlite3-intro">SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.</p> <p>The <code>sqlite3</code> module was written by Gerhard Häring. It provides an SQL interface compliant with the DB-API 2.0 specification described by <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a>, and requires SQLite 3.7.15 or newer.</p> <p>This document includes four main sections:</p> <ul class="simple"> <li>
+<a class="reference internal" href="#sqlite3-tutorial"><span class="std std-ref">Tutorial</span></a> teaches how to use the <code>sqlite3</code> module.</li> <li>
+<a class="reference internal" href="#sqlite3-reference"><span class="std std-ref">Reference</span></a> describes the classes and functions this module defines.</li> <li>
+<a class="reference internal" href="#sqlite3-howtos"><span class="std std-ref">How-to guides</span></a> details how to handle specific tasks.</li> <li>
+<a class="reference internal" href="#sqlite3-explanation"><span class="std std-ref">Explanation</span></a> provides in-depth background on transaction control.</li> </ul> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference external" href="https://www.sqlite.org">https://www.sqlite.org</a></dt>
+<dd>
+<p>The SQLite web page; the documentation describes the syntax and the available data types for the supported SQL dialect.</p> </dd> <dt><a class="reference external" href="https://www.w3schools.com/sql/">https://www.w3schools.com/sql/</a></dt>
+<dd>
+<p>Tutorial, reference and examples for learning SQL syntax.</p> </dd> <dt>
+<span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a> - Database API Specification 2.0</dt>
+<dd>
+<p>PEP written by Marc-André Lemburg.</p> </dd> </dl> </div> <section id="tutorial"> <span id="sqlite3-tutorial"></span><h2>Tutorial</h2> <p>In this tutorial, you will create a database of Monty Python movies using basic <code>sqlite3</code> functionality. It assumes a fundamental understanding of database concepts, including <a class="reference external" href="https://en.wikipedia.org/wiki/Cursor_(databases)">cursors</a> and <a class="reference external" href="https://en.wikipedia.org/wiki/Database_transaction">transactions</a>.</p> <p>First, we need to create a new database and open a database connection to allow <code>sqlite3</code> to work with it. Call <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code>sqlite3.connect()</code></a> to create a connection to the database <code>tutorial.db</code> in the current working directory, implicitly creating it if it does not exist:</p> <pre data-language="python">import sqlite3
+con = sqlite3.connect("tutorial.db")
+</pre> <p>The returned <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> object <code>con</code> represents the connection to the on-disk database.</p> <p>In order to execute SQL statements and fetch results from SQL queries, we will need to use a database cursor. Call <a class="reference internal" href="#sqlite3.Connection.cursor" title="sqlite3.Connection.cursor"><code>con.cursor()</code></a> to create the <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a>:</p> <pre data-language="python">cur = con.cursor()
+</pre> <p>Now that we’ve got a database connection and a cursor, we can create a database table <code>movie</code> with columns for title, release year, and review score. For simplicity, we can just use column names in the table declaration – thanks to the <a class="reference external" href="https://www.sqlite.org/flextypegood.html">flexible typing</a> feature of SQLite, specifying the data types is optional. Execute the <code>CREATE TABLE</code> statement by calling <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>cur.execute(...)</code></a>:</p> <pre data-language="python">cur.execute("CREATE TABLE movie(title, year, score)")
+</pre> <p>We can verify that the new table has been created by querying the <code>sqlite_master</code> table built-in to SQLite, which should now contain an entry for the <code>movie</code> table definition (see <a class="reference external" href="https://www.sqlite.org/schematab.html">The Schema Table</a> for details). Execute that query by calling <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>cur.execute(...)</code></a>, assign the result to <code>res</code>, and call <a class="reference internal" href="#sqlite3.Cursor.fetchone" title="sqlite3.Cursor.fetchone"><code>res.fetchone()</code></a> to fetch the resulting row:</p> <pre data-language="pycon3">&gt;&gt;&gt; res = cur.execute("SELECT name FROM sqlite_master")
+&gt;&gt;&gt; res.fetchone()
+('movie',)
+</pre> <p>We can see that the table has been created, as the query returns a <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> containing the table’s name. If we query <code>sqlite_master</code> for a non-existent table <code>spam</code>, <code>res.fetchone()</code> will return <code>None</code>:</p> <pre data-language="pycon3">&gt;&gt;&gt; res = cur.execute("SELECT name FROM sqlite_master WHERE name='spam'")
+&gt;&gt;&gt; res.fetchone() is None
+True
+</pre> <p>Now, add two rows of data supplied as SQL literals by executing an <code>INSERT</code> statement, once again by calling <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>cur.execute(...)</code></a>:</p> <pre data-language="python">cur.execute("""
+ INSERT INTO movie VALUES
+ ('Monty Python and the Holy Grail', 1975, 8.2),
+ ('And Now for Something Completely Different', 1971, 7.5)
+""")
+</pre> <p>The <code>INSERT</code> statement implicitly opens a transaction, which needs to be committed before changes are saved in the database (see <a class="reference internal" href="#sqlite3-controlling-transactions"><span class="std std-ref">Transaction control</span></a> for details). Call <a class="reference internal" href="#sqlite3.Connection.commit" title="sqlite3.Connection.commit"><code>con.commit()</code></a> on the connection object to commit the transaction:</p> <pre data-language="python">con.commit()
+</pre> <p>We can verify that the data was inserted correctly by executing a <code>SELECT</code> query. Use the now-familiar <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>cur.execute(...)</code></a> to assign the result to <code>res</code>, and call <a class="reference internal" href="#sqlite3.Cursor.fetchall" title="sqlite3.Cursor.fetchall"><code>res.fetchall()</code></a> to return all resulting rows:</p> <pre data-language="pycon3">&gt;&gt;&gt; res = cur.execute("SELECT score FROM movie")
+&gt;&gt;&gt; res.fetchall()
+[(8.2,), (7.5,)]
+</pre> <p>The result is a <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> of two <code>tuple</code>s, one per row, each containing that row’s <code>score</code> value.</p> <p>Now, insert three more rows by calling <a class="reference internal" href="#sqlite3.Cursor.executemany" title="sqlite3.Cursor.executemany"><code>cur.executemany(...)</code></a>:</p> <pre data-language="python">data = [
+ ("Monty Python Live at the Hollywood Bowl", 1982, 7.9),
+ ("Monty Python's The Meaning of Life", 1983, 7.5),
+ ("Monty Python's Life of Brian", 1979, 8.0),
+]
+cur.executemany("INSERT INTO movie VALUES(?, ?, ?)", data)
+con.commit() # Remember to commit the transaction after executing INSERT.
+</pre> <p>Notice that <code>?</code> placeholders are used to bind <code>data</code> to the query. Always use placeholders instead of <a class="reference internal" href="../tutorial/inputoutput#tut-formatting"><span class="std std-ref">string formatting</span></a> to bind Python values to SQL statements, to avoid <a class="reference external" href="https://en.wikipedia.org/wiki/SQL_injection">SQL injection attacks</a> (see <a class="reference internal" href="#sqlite3-placeholders"><span class="std std-ref">How to use placeholders to bind values in SQL queries</span></a> for more details).</p> <p>We can verify that the new rows were inserted by executing a <code>SELECT</code> query, this time iterating over the results of the query:</p> <pre data-language="pycon3">&gt;&gt;&gt; for row in cur.execute("SELECT year, title FROM movie ORDER BY year"):
+... print(row)
+(1971, 'And Now for Something Completely Different')
+(1975, 'Monty Python and the Holy Grail')
+(1979, "Monty Python's Life of Brian")
+(1982, 'Monty Python Live at the Hollywood Bowl')
+(1983, "Monty Python's The Meaning of Life")
+</pre> <p>Each row is a two-item <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> of <code>(year, title)</code>, matching the columns selected in the query.</p> <p>Finally, verify that the database has been written to disk by calling <a class="reference internal" href="#sqlite3.Connection.close" title="sqlite3.Connection.close"><code>con.close()</code></a> to close the existing connection, opening a new one, creating a new cursor, then querying the database:</p> <pre data-language="pycon3">&gt;&gt;&gt; con.close()
+&gt;&gt;&gt; new_con = sqlite3.connect("tutorial.db")
+&gt;&gt;&gt; new_cur = new_con.cursor()
+&gt;&gt;&gt; res = new_cur.execute("SELECT title, year FROM movie ORDER BY score DESC")
+&gt;&gt;&gt; title, year = res.fetchone()
+&gt;&gt;&gt; print(f'The highest scoring Monty Python movie is {title!r}, released in {year}')
+The highest scoring Monty Python movie is 'Monty Python and the Holy Grail', released in 1975
+</pre> <p>You’ve now created an SQLite database using the <code>sqlite3</code> module, inserted data and retrieved values from it in multiple ways.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li>
+<p><a class="reference internal" href="#sqlite3-howtos"><span class="std std-ref">How-to guides</span></a> for further reading:</p> <ul> <li><a class="reference internal" href="#sqlite3-placeholders"><span class="std std-ref">How to use placeholders to bind values in SQL queries</span></a></li> <li><a class="reference internal" href="#sqlite3-adapters"><span class="std std-ref">How to adapt custom Python types to SQLite values</span></a></li> <li><a class="reference internal" href="#sqlite3-converters"><span class="std std-ref">How to convert SQLite values to custom Python types</span></a></li> <li><a class="reference internal" href="#sqlite3-connection-context-manager"><span class="std std-ref">How to use the connection context manager</span></a></li> <li><a class="reference internal" href="#sqlite3-howto-row-factory"><span class="std std-ref">How to create and use row factories</span></a></li> </ul> </li> <li>
+<a class="reference internal" href="#sqlite3-explanation"><span class="std std-ref">Explanation</span></a> for in-depth background on transaction control.</li> </ul> </div> </section> <section id="reference"> <span id="sqlite3-reference"></span><h2>Reference</h2> <section id="module-functions"> <span id="sqlite3-module-functions"></span><span id="sqlite3-module-contents"></span><h3>Module functions</h3> <dl class="py function"> <dt class="sig sig-object py" id="sqlite3.connect">
+<code>sqlite3.connect(database, timeout=5.0, detect_types=0, isolation_level='DEFERRED', check_same_thread=True, factory=sqlite3.Connection, cached_statements=128, uri=False, *, autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL)</code> </dt> <dd>
+<p>Open a connection to an SQLite database.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>database</strong> (<a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>) – The path to the database file to be opened. You can pass <code>":memory:"</code> to create an <a class="reference external" href="https://sqlite.org/inmemorydb.html">SQLite database existing only in memory</a>, and open a connection to it.</li> <li>
+<strong>timeout</strong> (<a class="reference internal" href="functions#float" title="float">float</a>) – How many seconds the connection should wait before raising an <a class="reference internal" href="#sqlite3.OperationalError" title="sqlite3.OperationalError"><code>OperationalError</code></a> when a table is locked. If another connection opens a transaction to modify a table, that table will be locked until the transaction is committed. Default five seconds.</li> <li>
+<strong>detect_types</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – Control whether and how data types not <a class="reference internal" href="#sqlite3-types"><span class="std std-ref">natively supported by SQLite</span></a> are looked up to be converted to Python types, using the converters registered with <a class="reference internal" href="#sqlite3.register_converter" title="sqlite3.register_converter"><code>register_converter()</code></a>. Set it to any combination (using <code>|</code>, bitwise or) of <a class="reference internal" href="#sqlite3.PARSE_DECLTYPES" title="sqlite3.PARSE_DECLTYPES"><code>PARSE_DECLTYPES</code></a> and <a class="reference internal" href="#sqlite3.PARSE_COLNAMES" title="sqlite3.PARSE_COLNAMES"><code>PARSE_COLNAMES</code></a> to enable this. Column names takes precedence over declared types if both flags are set. Types cannot be detected for generated fields (for example <code>max(data)</code>), even when the <em>detect_types</em> parameter is set; <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> will be returned instead. By default (<code>0</code>), type detection is disabled.</li> <li>
+<strong>isolation_level</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a><em> | </em><em>None</em>) – Control legacy transaction handling behaviour. See <a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code>Connection.isolation_level</code></a> and <a class="reference internal" href="#sqlite3-transaction-control-isolation-level"><span class="std std-ref">Transaction control via the isolation_level attribute</span></a> for more information. Can be <code>"DEFERRED"</code> (default), <code>"EXCLUSIVE"</code> or <code>"IMMEDIATE"</code>; or <code>None</code> to disable opening transactions implicitly. Has no effect unless <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>Connection.autocommit</code></a> is set to <a class="reference internal" href="#sqlite3.LEGACY_TRANSACTION_CONTROL" title="sqlite3.LEGACY_TRANSACTION_CONTROL"><code>LEGACY_TRANSACTION_CONTROL</code></a> (the default).</li> <li>
+<strong>check_same_thread</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – If <code>True</code> (default), <a class="reference internal" href="#sqlite3.ProgrammingError" title="sqlite3.ProgrammingError"><code>ProgrammingError</code></a> will be raised if the database connection is used by a thread other than the one that created it. If <code>False</code>, the connection may be accessed in multiple threads; write operations may need to be serialized by the user to avoid data corruption. See <a class="reference internal" href="#sqlite3.threadsafety" title="sqlite3.threadsafety"><code>threadsafety</code></a> for more information.</li> <li>
+<strong>factory</strong> (<a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection">Connection</a>) – A custom subclass of <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> to create the connection with, if not the default <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> class.</li> <li>
+<strong>cached_statements</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – The number of statements that <code>sqlite3</code> should internally cache for this connection, to avoid parsing overhead. By default, 128 statements.</li> <li>
+<strong>uri</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – If set to <code>True</code>, <em>database</em> is interpreted as a <abbr title="Uniform Resource Identifier">URI</abbr> with a file path and an optional query string. The scheme part <em>must</em> be <code>"file:"</code>, and the path can be relative or absolute. The query string allows passing parameters to SQLite, enabling various <a class="reference internal" href="#sqlite3-uri-tricks"><span class="std std-ref">How to work with SQLite URIs</span></a>.</li> <li>
+<strong>autocommit</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – Control <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a> transaction handling behaviour. See <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>Connection.autocommit</code></a> and <a class="reference internal" href="#sqlite3-transaction-control-autocommit"><span class="std std-ref">Transaction control via the autocommit attribute</span></a> for more information. <em>autocommit</em> currently defaults to <a class="reference internal" href="#sqlite3.LEGACY_TRANSACTION_CONTROL" title="sqlite3.LEGACY_TRANSACTION_CONTROL"><code>LEGACY_TRANSACTION_CONTROL</code></a>. The default will change to <code>False</code> in a future Python release.</li> </ul> </dd> <dt class="field-even">Return type</dt> <dd class="field-even">
+<p><a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection">Connection</a></p> </dd> </dl> <p class="audit-hook">Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>sqlite3.connect</code> with argument <code>database</code>.</p> <p class="audit-hook">Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>sqlite3.connect/handle</code> with argument <code>connection_handle</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4: </span>The <em>uri</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><em>database</em> can now also be a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>, not only a string.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10: </span>The <code>sqlite3.connect/handle</code> auditing event.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12: </span>The <em>autocommit</em> parameter.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="sqlite3.complete_statement">
+<code>sqlite3.complete_statement(statement)</code> </dt> <dd>
+<p>Return <code>True</code> if the string <em>statement</em> appears to contain one or more complete SQL statements. No syntactic verification or parsing of any kind is performed, other than checking that there are no unclosed string literals and the statement is terminated by a semicolon.</p> <p>For example:</p> <pre data-language="pycon3">&gt;&gt;&gt; sqlite3.complete_statement("SELECT foo FROM bar;")
+True
+&gt;&gt;&gt; sqlite3.complete_statement("SELECT foo")
+False
+</pre> <p>This function may be useful during command-line input to determine if the entered text seems to form a complete SQL statement, or if additional input is needed before calling <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>execute()</code></a>.</p> <p>See <code>runsource()</code> in <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/sqlite3/__main__.py">Lib/sqlite3/__main__.py</a> for real-world use.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="sqlite3.enable_callback_tracebacks">
+<code>sqlite3.enable_callback_tracebacks(flag, /)</code> </dt> <dd>
+<p>Enable or disable callback tracebacks. By default you will not get any tracebacks in user-defined functions, aggregates, converters, authorizer callbacks etc. If you want to debug them, you can call this function with <em>flag</em> set to <code>True</code>. Afterwards, you will get tracebacks from callbacks on <a class="reference internal" href="sys#sys.stderr" title="sys.stderr"><code>sys.stderr</code></a>. Use <code>False</code> to disable the feature again.</p> <p>Register an <a class="reference internal" href="sys#sys.unraisablehook" title="sys.unraisablehook"><code>unraisable hook handler</code></a> for an improved debug experience:</p> <pre data-language="pycon3">&gt;&gt;&gt; sqlite3.enable_callback_tracebacks(True)
+&gt;&gt;&gt; con = sqlite3.connect(":memory:")
+&gt;&gt;&gt; def evil_trace(stmt):
+... 5/0
+...
+&gt;&gt;&gt; con.set_trace_callback(evil_trace)
+&gt;&gt;&gt; def debug(unraisable):
+... print(f"{unraisable.exc_value!r} in callback {unraisable.object.__name__}")
+... print(f"Error message: {unraisable.err_msg}")
+&gt;&gt;&gt; import sys
+&gt;&gt;&gt; sys.unraisablehook = debug
+&gt;&gt;&gt; cur = con.execute("SELECT 1")
+ZeroDivisionError('division by zero') in callback evil_trace
+Error message: None
+</pre> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="sqlite3.register_adapter">
+<code>sqlite3.register_adapter(type, adapter, /)</code> </dt> <dd>
+<p>Register an <em>adapter</em> <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> to adapt the Python type <em>type</em> into an SQLite type. The adapter is called with a Python object of type <em>type</em> as its sole argument, and must return a value of a <a class="reference internal" href="#sqlite3-types"><span class="std std-ref">type that SQLite natively understands</span></a>.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="sqlite3.register_converter">
+<code>sqlite3.register_converter(typename, converter, /)</code> </dt> <dd>
+<p>Register the <em>converter</em> <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> to convert SQLite objects of type <em>typename</em> into a Python object of a specific type. The converter is invoked for all SQLite values of type <em>typename</em>; it is passed a <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> object and should return an object of the desired Python type. Consult the parameter <em>detect_types</em> of <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code>connect()</code></a> for information regarding how type detection works.</p> <p>Note: <em>typename</em> and the name of the type in your query are matched case-insensitively.</p> </dd>
+</dl> </section> <section id="module-constants"> <span id="sqlite3-module-constants"></span><h3>Module constants</h3> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.LEGACY_TRANSACTION_CONTROL">
+<code>sqlite3.LEGACY_TRANSACTION_CONTROL</code> </dt> <dd>
+<p>Set <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> to this constant to select old style (pre-Python 3.12) transaction control behaviour. See <a class="reference internal" href="#sqlite3-transaction-control-isolation-level"><span class="std std-ref">Transaction control via the isolation_level attribute</span></a> for more information.</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.PARSE_COLNAMES">
+<code>sqlite3.PARSE_COLNAMES</code> </dt> <dd>
+<p>Pass this flag value to the <em>detect_types</em> parameter of <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code>connect()</code></a> to look up a converter function by using the type name, parsed from the query column name, as the converter dictionary key. The type name must be wrapped in square brackets (<code>[]</code>).</p> <pre data-language="sql">SELECT p as "p [point]" FROM test; ! will look up converter "point"
+</pre> <p>This flag may be combined with <a class="reference internal" href="#sqlite3.PARSE_DECLTYPES" title="sqlite3.PARSE_DECLTYPES"><code>PARSE_DECLTYPES</code></a> using the <code>|</code> (bitwise or) operator.</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.PARSE_DECLTYPES">
+<code>sqlite3.PARSE_DECLTYPES</code> </dt> <dd>
+<p>Pass this flag value to the <em>detect_types</em> parameter of <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code>connect()</code></a> to look up a converter function using the declared types for each column. The types are declared when the database table is created. <code>sqlite3</code> will look up a converter function using the first word of the declared type as the converter dictionary key. For example:</p> <pre data-language="sql">CREATE TABLE test(
+ i integer primary key, ! will look up a converter named "integer"
+ p point, ! will look up a converter named "point"
+ n number(10) ! will look up a converter named "number"
+ )
+</pre> <p>This flag may be combined with <a class="reference internal" href="#sqlite3.PARSE_COLNAMES" title="sqlite3.PARSE_COLNAMES"><code>PARSE_COLNAMES</code></a> using the <code>|</code> (bitwise or) operator.</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.SQLITE_OK">
+<code>sqlite3.SQLITE_OK</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DENY">
+<code>sqlite3.SQLITE_DENY</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_IGNORE">
+<code>sqlite3.SQLITE_IGNORE</code> </dt> <dd>
+<p>Flags that should be returned by the <em>authorizer_callback</em> <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> passed to <a class="reference internal" href="#sqlite3.Connection.set_authorizer" title="sqlite3.Connection.set_authorizer"><code>Connection.set_authorizer()</code></a>, to indicate whether:</p> <ul class="simple"> <li>Access is allowed (<code>SQLITE_OK</code>),</li> <li>The SQL statement should be aborted with an error (<code>SQLITE_DENY</code>)</li> <li>The column should be treated as a <code>NULL</code> value (<code>SQLITE_IGNORE</code>)</li> </ul> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.apilevel">
+<code>sqlite3.apilevel</code> </dt> <dd>
+<p>String constant stating the supported DB-API level. Required by the DB-API. Hard-coded to <code>"2.0"</code>.</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.paramstyle">
+<code>sqlite3.paramstyle</code> </dt> <dd>
+<p>String constant stating the type of parameter marker formatting expected by the <code>sqlite3</code> module. Required by the DB-API. Hard-coded to <code>"qmark"</code>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <code>named</code> DB-API parameter style is also supported.</p> </div> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.sqlite_version">
+<code>sqlite3.sqlite_version</code> </dt> <dd>
+<p>Version number of the runtime SQLite library as a <a class="reference internal" href="stdtypes#str" title="str"><code>string</code></a>.</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.sqlite_version_info">
+<code>sqlite3.sqlite_version_info</code> </dt> <dd>
+<p>Version number of the runtime SQLite library as a <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> of <a class="reference internal" href="functions#int" title="int"><code>integers</code></a>.</p> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.threadsafety">
+<code>sqlite3.threadsafety</code> </dt> <dd>
+<p>Integer constant required by the DB-API 2.0, stating the level of thread safety the <code>sqlite3</code> module supports. This attribute is set based on the default <a class="reference external" href="https://sqlite.org/threadsafe.html">threading mode</a> the underlying SQLite library is compiled with. The SQLite threading modes are:</p> <ol class="arabic simple"> <li>
+<strong>Single-thread</strong>: In this mode, all mutexes are disabled and SQLite is unsafe to use in more than a single thread at once.</li> <li>
+<strong>Multi-thread</strong>: In this mode, SQLite can be safely used by multiple threads provided that no single database connection is used simultaneously in two or more threads.</li> <li>
+<strong>Serialized</strong>: In serialized mode, SQLite can be safely used by multiple threads with no restriction.</li> </ol> <p>The mappings from SQLite threading modes to DB-API 2.0 threadsafety levels are as follows:</p> <table class="docutils align-default"> <thead> <tr>
+<th class="head"><p>SQLite threading mode</p></th> <th class="head"><p><a class="reference external" href="https://peps.python.org/pep-0249/#threadsafety">threadsafety</a></p></th> <th class="head"><p><a class="reference external" href="https://sqlite.org/compile.html#threadsafe">SQLITE_THREADSAFE</a></p></th> <th class="head"><p>DB-API 2.0 meaning</p></th> </tr> </thead> <tr>
+<td><p>single-thread</p></td> <td><p>0</p></td> <td><p>0</p></td> <td><p>Threads may not share the module</p></td> </tr> <tr>
+<td><p>multi-thread</p></td> <td><p>1</p></td> <td><p>2</p></td> <td><p>Threads may share the module, but not connections</p></td> </tr> <tr>
+<td><p>serialized</p></td> <td><p>3</p></td> <td><p>1</p></td> <td><p>Threads may share the module, connections and cursors</p></td> </tr> </table> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Set <em>threadsafety</em> dynamically instead of hard-coding it to <code>1</code>.</p> </div> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.version">
+<code>sqlite3.version</code> </dt> <dd>
+<p>Version number of this module as a <a class="reference internal" href="stdtypes#str" title="str"><code>string</code></a>. This is not the version of the SQLite library.</p> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.12, will be removed in version 3.14: </span>This constant used to reflect the version number of the <code>pysqlite</code> package, a third-party library which used to upstream changes to <code>sqlite3</code>. Today, it carries no meaning or practical value.</p> </div> </dd>
+</dl> <dl class="py data"> <dt class="sig sig-object py" id="sqlite3.version_info">
+<code>sqlite3.version_info</code> </dt> <dd>
+<p>Version number of this module as a <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> of <a class="reference internal" href="functions#int" title="int"><code>integers</code></a>. This is not the version of the SQLite library.</p> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.12, will be removed in version 3.14: </span>This constant used to reflect the version number of the <code>pysqlite</code> package, a third-party library which used to upstream changes to <code>sqlite3</code>. Today, it carries no meaning or practical value.</p> </div> </dd>
+</dl> <span class="target" id="sqlite3-dbconfig-constants"></span><dl class="py data"> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_DEFENSIVE">
+<code>sqlite3.SQLITE_DBCONFIG_DEFENSIVE</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_DQS_DDL">
+<code>sqlite3.SQLITE_DBCONFIG_DQS_DDL</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_DQS_DML">
+<code>sqlite3.SQLITE_DBCONFIG_DQS_DML</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_ENABLE_FKEY">
+<code>sqlite3.SQLITE_DBCONFIG_ENABLE_FKEY</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER">
+<code>sqlite3.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION">
+<code>sqlite3.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_ENABLE_QPSG">
+<code>sqlite3.SQLITE_DBCONFIG_ENABLE_QPSG</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_ENABLE_TRIGGER">
+<code>sqlite3.SQLITE_DBCONFIG_ENABLE_TRIGGER</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_ENABLE_VIEW">
+<code>sqlite3.SQLITE_DBCONFIG_ENABLE_VIEW</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE">
+<code>sqlite3.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT">
+<code>sqlite3.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE">
+<code>sqlite3.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_RESET_DATABASE">
+<code>sqlite3.SQLITE_DBCONFIG_RESET_DATABASE</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_TRIGGER_EQP">
+<code>sqlite3.SQLITE_DBCONFIG_TRIGGER_EQP</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_TRUSTED_SCHEMA">
+<code>sqlite3.SQLITE_DBCONFIG_TRUSTED_SCHEMA</code> </dt> <dt class="sig sig-object py" id="sqlite3.SQLITE_DBCONFIG_WRITABLE_SCHEMA">
+<code>sqlite3.SQLITE_DBCONFIG_WRITABLE_SCHEMA</code> </dt> <dd>
+<p>These constants are used for the <a class="reference internal" href="#sqlite3.Connection.setconfig" title="sqlite3.Connection.setconfig"><code>Connection.setconfig()</code></a> and <a class="reference internal" href="#sqlite3.Connection.getconfig" title="sqlite3.Connection.getconfig"><code>getconfig()</code></a> methods.</p> <p>The availability of these constants varies depending on the version of SQLite Python was compiled with.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference external" href="https://www.sqlite.org/c3ref/c_dbconfig_defensive.html">https://www.sqlite.org/c3ref/c_dbconfig_defensive.html</a></dt>
+<dd>
+<p>SQLite docs: Database Connection Configuration Options</p> </dd> </dl> </div> </dd>
+</dl> </section> <section id="connection-objects"> <span id="sqlite3-connection-objects"></span><h3>Connection objects</h3> <dl class="py class"> <dt class="sig sig-object py" id="sqlite3.Connection">
+<code>class sqlite3.Connection</code> </dt> <dd>
+<p>Each open SQLite database is represented by a <code>Connection</code> object, which is created using <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code>sqlite3.connect()</code></a>. Their main purpose is creating <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> objects, and <a class="reference internal" href="#sqlite3-controlling-transactions"><span class="std std-ref">Transaction control</span></a>.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li><a class="reference internal" href="#sqlite3-connection-shortcuts"><span class="std std-ref">How to use connection shortcut methods</span></a></li> <li><a class="reference internal" href="#sqlite3-connection-context-manager"><span class="std std-ref">How to use the connection context manager</span></a></li> </ul> </div> <p>An SQLite database connection has the following attributes and methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.cursor">
+<code>cursor(factory=Cursor)</code> </dt> <dd>
+<p>Create and return a <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> object. The cursor method accepts a single optional parameter <em>factory</em>. If supplied, this must be a <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> returning an instance of <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> or its subclasses.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.blobopen">
+<code>blobopen(table, column, row, /, *, readonly=False, name='main')</code> </dt> <dd>
+<p>Open a <a class="reference internal" href="#sqlite3.Blob" title="sqlite3.Blob"><code>Blob</code></a> handle to an existing <abbr title="Binary Large OBject">BLOB</abbr>.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>table</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The name of the table where the blob is located.</li> <li>
+<strong>column</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The name of the column where the blob is located.</li> <li>
+<strong>row</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The name of the row where the blob is located.</li> <li>
+<strong>readonly</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – Set to <code>True</code> if the blob should be opened without write permissions. Defaults to <code>False</code>.</li> <li>
+<strong>name</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The name of the database where the blob is located. Defaults to <code>"main"</code>.</li> </ul> </dd> <dt class="field-even">Raises</dt> <dd class="field-even">
+<p><a class="reference internal" href="#sqlite3.OperationalError" title="sqlite3.OperationalError"><strong>OperationalError</strong></a> – When trying to open a blob in a <code>WITHOUT ROWID</code> table.</p> </dd> <dt class="field-odd">Return type</dt> <dd class="field-odd">
+<p><a class="reference internal" href="#sqlite3.Blob" title="sqlite3.Blob">Blob</a></p> </dd> </dl> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The blob size cannot be changed using the <a class="reference internal" href="#sqlite3.Blob" title="sqlite3.Blob"><code>Blob</code></a> class. Use the SQL function <code>zeroblob</code> to create a blob with a fixed size.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.commit">
+<code>commit()</code> </dt> <dd>
+<p>Commit any pending transaction to the database. If <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> is <code>True</code>, or there is no open transaction, this method does nothing. If <code>autocommit</code> is <code>False</code>, a new transaction is implicitly opened if a pending transaction was committed by this method.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.rollback">
+<code>rollback()</code> </dt> <dd>
+<p>Roll back to the start of any pending transaction. If <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> is <code>True</code>, or there is no open transaction, this method does nothing. If <code>autocommit</code> is <code>False</code>, a new transaction is implicitly opened if a pending transaction was rolled back by this method.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.close">
+<code>close()</code> </dt> <dd>
+<p>Close the database connection. If <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> is <code>False</code>, any pending transaction is implicitly rolled back. If <code>autocommit</code> is <code>True</code> or <a class="reference internal" href="#sqlite3.LEGACY_TRANSACTION_CONTROL" title="sqlite3.LEGACY_TRANSACTION_CONTROL"><code>LEGACY_TRANSACTION_CONTROL</code></a>, no implicit transaction control is executed. Make sure to <a class="reference internal" href="#sqlite3.Connection.commit" title="sqlite3.Connection.commit"><code>commit()</code></a> before closing to avoid losing pending changes.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.execute">
+<code>execute(sql, parameters=(), /)</code> </dt> <dd>
+<p>Create a new <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> object and call <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>execute()</code></a> on it with the given <em>sql</em> and <em>parameters</em>. Return the new cursor object.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.executemany">
+<code>executemany(sql, parameters, /)</code> </dt> <dd>
+<p>Create a new <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> object and call <a class="reference internal" href="#sqlite3.Cursor.executemany" title="sqlite3.Cursor.executemany"><code>executemany()</code></a> on it with the given <em>sql</em> and <em>parameters</em>. Return the new cursor object.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.executescript">
+<code>executescript(sql_script, /)</code> </dt> <dd>
+<p>Create a new <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> object and call <a class="reference internal" href="#sqlite3.Cursor.executescript" title="sqlite3.Cursor.executescript"><code>executescript()</code></a> on it with the given <em>sql_script</em>. Return the new cursor object.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.create_function">
+<code>create_function(name, narg, func, *, deterministic=False)</code> </dt> <dd>
+<p>Create or remove a user-defined SQL function.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>name</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The name of the SQL function.</li> <li>
+<strong>narg</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – The number of arguments the SQL function can accept. If <code>-1</code>, it may take any number of arguments.</li> <li>
+<strong>func</strong> (<a class="reference internal" href="../glossary#term-callback"><span class="xref std std-term">callback</span></a> | None) – A <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> that is called when the SQL function is invoked. The callable must return <a class="reference internal" href="#sqlite3-types"><span class="std std-ref">a type natively supported by SQLite</span></a>. Set to <code>None</code> to remove an existing SQL function.</li> <li>
+<strong>deterministic</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – If <code>True</code>, the created SQL function is marked as <a class="reference external" href="https://sqlite.org/deterministic.html">deterministic</a>, which allows SQLite to perform additional optimizations.</li> </ul> </dd> <dt class="field-even">Raises</dt> <dd class="field-even">
+<p><a class="reference internal" href="#sqlite3.NotSupportedError" title="sqlite3.NotSupportedError"><strong>NotSupportedError</strong></a> – If <em>deterministic</em> is used with SQLite versions older than 3.8.3.</p> </dd> </dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8: </span>The <em>deterministic</em> parameter.</p> </div> <p>Example:</p> <pre data-language="pycon3">&gt;&gt;&gt; import hashlib
+&gt;&gt;&gt; def md5sum(t):
+... return hashlib.md5(t).hexdigest()
+&gt;&gt;&gt; con = sqlite3.connect(":memory:")
+&gt;&gt;&gt; con.create_function("md5", 1, md5sum)
+&gt;&gt;&gt; for row in con.execute("SELECT md5(?)", (b"foo",)):
+... print(row)
+('acbd18db4cc2f85cedef654fccc4a4d8',)
+</pre> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.create_aggregate">
+<code>create_aggregate(name, n_arg, aggregate_class)</code> </dt> <dd>
+<p>Create or remove a user-defined SQL aggregate function.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>name</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The name of the SQL aggregate function.</li> <li>
+<strong>n_arg</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – The number of arguments the SQL aggregate function can accept. If <code>-1</code>, it may take any number of arguments.</li> <li>
+<p><strong>aggregate_class</strong> (<a class="reference internal" href="../glossary#term-class"><span class="xref std std-term">class</span></a> | None) – </p>
+<p>A class must implement the following methods:</p> <ul> <li>
+<code>step()</code>: Add a row to the aggregate.</li> <li>
+<code>finalize()</code>: Return the final result of the aggregate as <a class="reference internal" href="#sqlite3-types"><span class="std std-ref">a type natively supported by SQLite</span></a>.</li> </ul> <p>The number of arguments that the <code>step()</code> method must accept is controlled by <em>n_arg</em>.</p> <p>Set to <code>None</code> to remove an existing SQL aggregate function.</p> </li> </ul> </dd> </dl> <p>Example:</p> <pre data-language="python">class MySum:
+ def __init__(self):
+ self.count = 0
+
+ def step(self, value):
+ self.count += value
+
+ def finalize(self):
+ return self.count
+
+con = sqlite3.connect(":memory:")
+con.create_aggregate("mysum", 1, MySum)
+cur = con.execute("CREATE TABLE test(i)")
+cur.execute("INSERT INTO test(i) VALUES(1)")
+cur.execute("INSERT INTO test(i) VALUES(2)")
+cur.execute("SELECT mysum(i) FROM test")
+print(cur.fetchone()[0])
+
+con.close()
+</pre> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.create_window_function">
+<code>create_window_function(name, num_params, aggregate_class, /)</code> </dt> <dd>
+<p>Create or remove a user-defined aggregate window function.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>name</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The name of the SQL aggregate window function to create or remove.</li> <li>
+<strong>num_params</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – The number of arguments the SQL aggregate window function can accept. If <code>-1</code>, it may take any number of arguments.</li> <li>
+<p><strong>aggregate_class</strong> (<a class="reference internal" href="../glossary#term-class"><span class="xref std std-term">class</span></a> | None) – </p>
+<p>A class that must implement the following methods:</p> <ul> <li>
+<code>step()</code>: Add a row to the current window.</li> <li>
+<code>value()</code>: Return the current value of the aggregate.</li> <li>
+<code>inverse()</code>: Remove a row from the current window.</li> <li>
+<code>finalize()</code>: Return the final result of the aggregate as <a class="reference internal" href="#sqlite3-types"><span class="std std-ref">a type natively supported by SQLite</span></a>.</li> </ul> <p>The number of arguments that the <code>step()</code> and <code>value()</code> methods must accept is controlled by <em>num_params</em>.</p> <p>Set to <code>None</code> to remove an existing SQL aggregate window function.</p> </li> </ul> </dd> <dt class="field-even">Raises</dt> <dd class="field-even">
+<p><a class="reference internal" href="#sqlite3.NotSupportedError" title="sqlite3.NotSupportedError"><strong>NotSupportedError</strong></a> – If used with a version of SQLite older than 3.25.0, which does not support aggregate window functions.</p> </dd> </dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> <p>Example:</p> <pre data-language="python"># Example taken from https://www.sqlite.org/windowfunctions.html#udfwinfunc
+class WindowSumInt:
+ def __init__(self):
+ self.count = 0
+
+ def step(self, value):
+ """Add a row to the current window."""
+ self.count += value
+
+ def value(self):
+ """Return the current value of the aggregate."""
+ return self.count
+
+ def inverse(self, value):
+ """Remove a row from the current window."""
+ self.count -= value
+
+ def finalize(self):
+ """Return the final value of the aggregate.
+
+ Any clean-up actions should be placed here.
+ """
+ return self.count
+
+
+con = sqlite3.connect(":memory:")
+cur = con.execute("CREATE TABLE test(x, y)")
+values = [
+ ("a", 4),
+ ("b", 5),
+ ("c", 3),
+ ("d", 8),
+ ("e", 1),
+]
+cur.executemany("INSERT INTO test VALUES(?, ?)", values)
+con.create_window_function("sumint", 1, WindowSumInt)
+cur.execute("""
+ SELECT x, sumint(y) OVER (
+ ORDER BY x ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
+ ) AS sum_y
+ FROM test ORDER BY x
+""")
+print(cur.fetchall())
+</pre> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.create_collation">
+<code>create_collation(name, callable, /)</code> </dt> <dd>
+<p>Create a collation named <em>name</em> using the collating function <em>callable</em>. <em>callable</em> is passed two <a class="reference internal" href="stdtypes#str" title="str"><code>string</code></a> arguments, and it should return an <a class="reference internal" href="functions#int" title="int"><code>integer</code></a>:</p> <ul class="simple"> <li>
+<code>1</code> if the first is ordered higher than the second</li> <li>
+<code>-1</code> if the first is ordered lower than the second</li> <li>
+<code>0</code> if they are ordered equal</li> </ul> <p>The following example shows a reverse sorting collation:</p> <pre data-language="python">def collate_reverse(string1, string2):
+ if string1 == string2:
+ return 0
+ elif string1 &lt; string2:
+ return 1
+ else:
+ return -1
+
+con = sqlite3.connect(":memory:")
+con.create_collation("reverse", collate_reverse)
+
+cur = con.execute("CREATE TABLE test(x)")
+cur.executemany("INSERT INTO test(x) VALUES(?)", [("a",), ("b",)])
+cur.execute("SELECT x FROM test ORDER BY x COLLATE reverse")
+for row in cur:
+ print(row)
+con.close()
+</pre> <p>Remove a collation function by setting <em>callable</em> to <code>None</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The collation name can contain any Unicode character. Earlier, only ASCII characters were allowed.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.interrupt">
+<code>interrupt()</code> </dt> <dd>
+<p>Call this method from a different thread to abort any queries that might be executing on the connection. Aborted queries will raise an <a class="reference internal" href="#sqlite3.OperationalError" title="sqlite3.OperationalError"><code>OperationalError</code></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.set_authorizer">
+<code>set_authorizer(authorizer_callback)</code> </dt> <dd>
+<p>Register <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> <em>authorizer_callback</em> to be invoked for each attempt to access a column of a table in the database. The callback should return one of <a class="reference internal" href="#sqlite3.SQLITE_OK" title="sqlite3.SQLITE_OK"><code>SQLITE_OK</code></a>, <a class="reference internal" href="#sqlite3.SQLITE_DENY" title="sqlite3.SQLITE_DENY"><code>SQLITE_DENY</code></a>, or <a class="reference internal" href="#sqlite3.SQLITE_IGNORE" title="sqlite3.SQLITE_IGNORE"><code>SQLITE_IGNORE</code></a> to signal how access to the column should be handled by the underlying SQLite library.</p> <p>The first argument to the callback signifies what kind of operation is to be authorized. The second and third argument will be arguments or <code>None</code> depending on the first argument. The 4th argument is the name of the database (“main”, “temp”, etc.) if applicable. The 5th argument is the name of the inner-most trigger or view that is responsible for the access attempt or <code>None</code> if this access attempt is directly from input SQL code.</p> <p>Please consult the SQLite documentation about the possible values for the first argument and the meaning of the second and third argument depending on the first one. All necessary constants are available in the <code>sqlite3</code> module.</p> <p>Passing <code>None</code> as <em>authorizer_callback</em> will disable the authorizer.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added support for disabling the authorizer using <code>None</code>.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.set_progress_handler">
+<code>set_progress_handler(progress_handler, n)</code> </dt> <dd>
+<p>Register <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> <em>progress_handler</em> to be invoked for every <em>n</em> instructions of the SQLite virtual machine. This is useful if you want to get called from SQLite during long-running operations, for example to update a GUI.</p> <p>If you want to clear any previously installed progress handler, call the method with <code>None</code> for <em>progress_handler</em>.</p> <p>Returning a non-zero value from the handler function will terminate the currently executing query and cause it to raise a <a class="reference internal" href="#sqlite3.DatabaseError" title="sqlite3.DatabaseError"><code>DatabaseError</code></a> exception.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.set_trace_callback">
+<code>set_trace_callback(trace_callback)</code> </dt> <dd>
+<p>Register <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> <em>trace_callback</em> to be invoked for each SQL statement that is actually executed by the SQLite backend.</p> <p>The only argument passed to the callback is the statement (as <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>) that is being executed. The return value of the callback is ignored. Note that the backend does not only run statements passed to the <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>Cursor.execute()</code></a> methods. Other sources include the <a class="reference internal" href="#sqlite3-controlling-transactions"><span class="std std-ref">transaction management</span></a> of the <code>sqlite3</code> module and the execution of triggers defined in the current database.</p> <p>Passing <code>None</code> as <em>trace_callback</em> will disable the trace callback.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Exceptions raised in the trace callback are not propagated. As a development and debugging aid, use <a class="reference internal" href="#sqlite3.enable_callback_tracebacks" title="sqlite3.enable_callback_tracebacks"><code>enable_callback_tracebacks()</code></a> to enable printing tracebacks from exceptions raised in the trace callback.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.enable_load_extension">
+<code>enable_load_extension(enabled, /)</code> </dt> <dd>
+<p>Enable the SQLite engine to load SQLite extensions from shared libraries if <em>enabled</em> is <code>True</code>; else, disallow loading SQLite extensions. SQLite extensions can define new functions, aggregates or whole new virtual table implementations. One well-known extension is the fulltext-search extension distributed with SQLite.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <code>sqlite3</code> module is not built with loadable extension support by default, because some platforms (notably macOS) have SQLite libraries which are compiled without this feature. To get loadable extension support, you must pass the <a class="reference internal" href="../using/configure#cmdoption-enable-loadable-sqlite-extensions"><code>--enable-loadable-sqlite-extensions</code></a> option to <strong class="program">configure</strong>.</p> </div> <p class="audit-hook">Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>sqlite3.enable_load_extension</code> with arguments <code>connection</code>, <code>enabled</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Added the <code>sqlite3.enable_load_extension</code> auditing event.</p> </div> <pre data-language="python">con.enable_load_extension(True)
+
+# Load the fulltext search extension
+con.execute("select load_extension('./fts3.so')")
+
+# alternatively you can load the extension using an API call:
+# con.load_extension("./fts3.so")
+
+# disable extension loading again
+con.enable_load_extension(False)
+
+# example from SQLite wiki
+con.execute("CREATE VIRTUAL TABLE recipe USING fts3(name, ingredients)")
+con.executescript("""
+ INSERT INTO recipe (name, ingredients) VALUES('broccoli stew', 'broccoli peppers cheese tomatoes');
+ INSERT INTO recipe (name, ingredients) VALUES('pumpkin stew', 'pumpkin onions garlic celery');
+ INSERT INTO recipe (name, ingredients) VALUES('broccoli pie', 'broccoli cheese onions flour');
+ INSERT INTO recipe (name, ingredients) VALUES('pumpkin pie', 'pumpkin sugar flour butter');
+ """)
+for row in con.execute("SELECT rowid, name, ingredients FROM recipe WHERE name MATCH 'pie'"):
+ print(row)
+
+con.close()
+</pre> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.load_extension">
+<code>load_extension(path, /, *, entrypoint=None)</code> </dt> <dd>
+<p>Load an SQLite extension from a shared library. Enable extension loading with <a class="reference internal" href="#sqlite3.Connection.enable_load_extension" title="sqlite3.Connection.enable_load_extension"><code>enable_load_extension()</code></a> before calling this method.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>path</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The path to the SQLite extension.</li> <li>
+<strong>entrypoint</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a><em> | </em><em>None</em>) – Entry point name. If <code>None</code> (the default), SQLite will come up with an entry point name of its own; see the SQLite docs <a class="reference external" href="https://www.sqlite.org/loadext.html#loading_an_extension_">Loading an Extension</a> for details.</li> </ul> </dd> </dl> <p class="audit-hook">Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>sqlite3.load_extension</code> with arguments <code>connection</code>, <code>path</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Added the <code>sqlite3.load_extension</code> auditing event.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12: </span>The <em>entrypoint</em> parameter.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.iterdump">
+<code>iterdump()</code> </dt> <dd>
+<p>Return an <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a> to dump the database as SQL source code. Useful when saving an in-memory database for later restoration. Similar to the <code>.dump</code> command in the <strong class="program">sqlite3</strong> shell.</p> <p>Example:</p> <pre data-language="python"># Convert file example.db to SQL dump file dump.sql
+con = sqlite3.connect('example.db')
+with open('dump.sql', 'w') as f:
+ for line in con.iterdump():
+ f.write('%s\n' % line)
+con.close()
+</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="#sqlite3-howto-encoding"><span class="std std-ref">How to handle non-UTF-8 text encodings</span></a></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.backup">
+<code>backup(target, *, pages=- 1, progress=None, name='main', sleep=0.250)</code> </dt> <dd>
+<p>Create a backup of an SQLite database.</p> <p>Works even if the database is being accessed by other clients or concurrently by the same connection.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>target</strong> (<a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection">Connection</a>) – The database connection to save the backup to.</li> <li>
+<strong>pages</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – The number of pages to copy at a time. If equal to or less than <code>0</code>, the entire database is copied in a single step. Defaults to <code>-1</code>.</li> <li>
+<strong>progress</strong> (<a class="reference internal" href="../glossary#term-callback"><span class="xref std std-term">callback</span></a> | None) – If set to a <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a>, it is invoked with three integer arguments for every backup iteration: the <em>status</em> of the last iteration, the <em>remaining</em> number of pages still to be copied, and the <em>total</em> number of pages. Defaults to <code>None</code>.</li> <li>
+<strong>name</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The name of the database to back up. Either <code>"main"</code> (the default) for the main database, <code>"temp"</code> for the temporary database, or the name of a custom database as attached using the <code>ATTACH DATABASE</code> SQL statement.</li> <li>
+<strong>sleep</strong> (<a class="reference internal" href="functions#float" title="float">float</a>) – The number of seconds to sleep between successive attempts to back up remaining pages.</li> </ul> </dd> </dl> <p>Example 1, copy an existing database into another:</p> <pre data-language="python">def progress(status, remaining, total):
+ print(f'Copied {total-remaining} of {total} pages...')
+
+src = sqlite3.connect('example.db')
+dst = sqlite3.connect('backup.db')
+with dst:
+ src.backup(dst, pages=1, progress=progress)
+dst.close()
+src.close()
+</pre> <p>Example 2, copy an existing database into a transient copy:</p> <pre data-language="python">src = sqlite3.connect('example.db')
+dst = sqlite3.connect(':memory:')
+src.backup(dst)
+</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="#sqlite3-howto-encoding"><span class="std std-ref">How to handle non-UTF-8 text encodings</span></a></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.getlimit">
+<code>getlimit(category, /)</code> </dt> <dd>
+<p>Get a connection runtime limit.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<p><strong>category</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – The <a class="reference external" href="https://www.sqlite.org/c3ref/c_limit_attached.html">SQLite limit category</a> to be queried.</p> </dd> <dt class="field-even">Return type</dt> <dd class="field-even">
+<p><a class="reference internal" href="functions#int" title="int">int</a></p> </dd> <dt class="field-odd">Raises</dt> <dd class="field-odd">
+<p><a class="reference internal" href="#sqlite3.ProgrammingError" title="sqlite3.ProgrammingError"><strong>ProgrammingError</strong></a> – If <em>category</em> is not recognised by the underlying SQLite library.</p> </dd> </dl> <p>Example, query the maximum length of an SQL statement for <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> <code>con</code> (the default is 1000000000):</p> <pre data-language="pycon3">&gt;&gt;&gt; con.getlimit(sqlite3.SQLITE_LIMIT_SQL_LENGTH)
+1000000000
+</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.setlimit">
+<code>setlimit(category, limit, /)</code> </dt> <dd>
+<p>Set a connection runtime limit. Attempts to increase a limit above its hard upper bound are silently truncated to the hard upper bound. Regardless of whether or not the limit was changed, the prior value of the limit is returned.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>category</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – The <a class="reference external" href="https://www.sqlite.org/c3ref/c_limit_attached.html">SQLite limit category</a> to be set.</li> <li>
+<strong>limit</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – The value of the new limit. If negative, the current limit is unchanged.</li> </ul> </dd> <dt class="field-even">Return type</dt> <dd class="field-even">
+<p><a class="reference internal" href="functions#int" title="int">int</a></p> </dd> <dt class="field-odd">Raises</dt> <dd class="field-odd">
+<p><a class="reference internal" href="#sqlite3.ProgrammingError" title="sqlite3.ProgrammingError"><strong>ProgrammingError</strong></a> – If <em>category</em> is not recognised by the underlying SQLite library.</p> </dd> </dl> <p>Example, limit the number of attached databases to 1 for <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> <code>con</code> (the default limit is 10):</p> <pre data-language="pycon3">&gt;&gt;&gt; con.setlimit(sqlite3.SQLITE_LIMIT_ATTACHED, 1)
+10
+&gt;&gt;&gt; con.getlimit(sqlite3.SQLITE_LIMIT_ATTACHED)
+1
+</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.getconfig">
+<code>getconfig(op, /)</code> </dt> <dd>
+<p>Query a boolean connection configuration option.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<p><strong>op</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – A <a class="reference internal" href="#sqlite3-dbconfig-constants"><span class="std std-ref">SQLITE_DBCONFIG code</span></a>.</p> </dd> <dt class="field-even">Return type</dt> <dd class="field-even">
+<p><a class="reference internal" href="functions#bool" title="bool">bool</a></p> </dd> </dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.setconfig">
+<code>setconfig(op, enable=True, /)</code> </dt> <dd>
+<p>Set a boolean connection configuration option.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>op</strong> (<a class="reference internal" href="functions#int" title="int">int</a>) – A <a class="reference internal" href="#sqlite3-dbconfig-constants"><span class="std std-ref">SQLITE_DBCONFIG code</span></a>.</li> <li>
+<strong>enable</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – <code>True</code> if the configuration option should be enabled (default); <code>False</code> if it should be disabled.</li> </ul> </dd> </dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.serialize">
+<code>serialize(*, name='main')</code> </dt> <dd>
+<p>Serialize a database into a <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> object. For an ordinary on-disk database file, the serialization is just a copy of the disk file. For an in-memory database or a “temp” database, the serialization is the same sequence of bytes which would be written to disk if that database were backed up to disk.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<p><strong>name</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The database name to be serialized. Defaults to <code>"main"</code>.</p> </dd> <dt class="field-even">Return type</dt> <dd class="field-even">
+<p><a class="reference internal" href="stdtypes#bytes" title="bytes">bytes</a></p> </dd> </dl> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This method is only available if the underlying SQLite library has the serialize API.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Connection.deserialize">
+<code>deserialize(data, /, *, name='main')</code> </dt> <dd>
+<p>Deserialize a <a class="reference internal" href="#sqlite3.Connection.serialize" title="sqlite3.Connection.serialize"><code>serialized</code></a> database into a <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a>. This method causes the database connection to disconnect from database <em>name</em>, and reopen <em>name</em> as an in-memory database based on the serialization contained in <em>data</em>.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>data</strong> (<a class="reference internal" href="stdtypes#bytes" title="bytes">bytes</a>) – A serialized database.</li> <li>
+<strong>name</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – The database name to deserialize into. Defaults to <code>"main"</code>.</li> </ul> </dd> <dt class="field-even">Raises</dt> <dd class="field-even">
+<ul class="simple"> <li>
+<a class="reference internal" href="#sqlite3.OperationalError" title="sqlite3.OperationalError"><strong>OperationalError</strong></a> – If the database connection is currently involved in a read transaction or a backup operation.</li> <li>
+<a class="reference internal" href="#sqlite3.DatabaseError" title="sqlite3.DatabaseError"><strong>DatabaseError</strong></a> – If <em>data</em> does not contain a valid SQLite database.</li> <li>
+<a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><strong>OverflowError</strong></a> – If <a class="reference internal" href="functions#len" title="len"><code>len(data)</code></a> is larger than <code>2**63 - 1</code>.</li> </ul> </dd> </dl> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This method is only available if the underlying SQLite library has the deserialize API.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Connection.autocommit">
+<code>autocommit</code> </dt> <dd>
+<p>This attribute controls <span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a>-compliant transaction behaviour. <code>autocommit</code> has three allowed values:</p> <ul> <li>
+<p><code>False</code>: Select <span class="target" id="index-4"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a>-compliant transaction behaviour, implying that <code>sqlite3</code> ensures a transaction is always open. Use <a class="reference internal" href="#sqlite3.Connection.commit" title="sqlite3.Connection.commit"><code>commit()</code></a> and <a class="reference internal" href="#sqlite3.Connection.rollback" title="sqlite3.Connection.rollback"><code>rollback()</code></a> to close transactions.</p> <p>This is the recommended value of <code>autocommit</code>.</p> </li> <li>
+<code>True</code>: Use SQLite’s <a class="reference external" href="https://www.sqlite.org/lang_transaction.html#implicit_versus_explicit_transactions">autocommit mode</a>. <a class="reference internal" href="#sqlite3.Connection.commit" title="sqlite3.Connection.commit"><code>commit()</code></a> and <a class="reference internal" href="#sqlite3.Connection.rollback" title="sqlite3.Connection.rollback"><code>rollback()</code></a> have no effect in this mode.</li> <li>
+<p><a class="reference internal" href="#sqlite3.LEGACY_TRANSACTION_CONTROL" title="sqlite3.LEGACY_TRANSACTION_CONTROL"><code>LEGACY_TRANSACTION_CONTROL</code></a>: Pre-Python 3.12 (non-<span class="target" id="index-5"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a>-compliant) transaction control. See <a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code>isolation_level</code></a> for more details.</p> <p>This is currently the default value of <code>autocommit</code>.</p> </li> </ul> <p>Changing <code>autocommit</code> to <code>False</code> will open a new transaction, and changing it to <code>True</code> will commit any pending transaction.</p> <p>See <a class="reference internal" href="#sqlite3-transaction-control-autocommit"><span class="std std-ref">Transaction control via the autocommit attribute</span></a> for more details.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code>isolation_level</code></a> attribute has no effect unless <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> is <a class="reference internal" href="#sqlite3.LEGACY_TRANSACTION_CONTROL" title="sqlite3.LEGACY_TRANSACTION_CONTROL"><code>LEGACY_TRANSACTION_CONTROL</code></a>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Connection.in_transaction">
+<code>in_transaction</code> </dt> <dd>
+<p>This read-only attribute corresponds to the low-level SQLite <a class="reference external" href="https://www.sqlite.org/lang_transaction.html#implicit_versus_explicit_transactions">autocommit mode</a>.</p> <p><code>True</code> if a transaction is active (there are uncommitted changes), <code>False</code> otherwise.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Connection.isolation_level">
+<code>isolation_level</code> </dt> <dd>
+<p>Controls the <a class="reference internal" href="#sqlite3-transaction-control-isolation-level"><span class="std std-ref">legacy transaction handling mode</span></a> of <code>sqlite3</code>. If set to <code>None</code>, transactions are never implicitly opened. If set to one of <code>"DEFERRED"</code>, <code>"IMMEDIATE"</code>, or <code>"EXCLUSIVE"</code>, corresponding to the underlying <a class="reference external" href="https://www.sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions">SQLite transaction behaviour</a>, <a class="reference internal" href="#sqlite3-transaction-control-isolation-level"><span class="std std-ref">implicit transaction management</span></a> is performed.</p> <p>If not overridden by the <em>isolation_level</em> parameter of <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code>connect()</code></a>, the default is <code>""</code>, which is an alias for <code>"DEFERRED"</code>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Using <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> to control transaction handling is recommended over using <code>isolation_level</code>. <code>isolation_level</code> has no effect unless <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> is set to <a class="reference internal" href="#sqlite3.LEGACY_TRANSACTION_CONTROL" title="sqlite3.LEGACY_TRANSACTION_CONTROL"><code>LEGACY_TRANSACTION_CONTROL</code></a> (the default).</p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Connection.row_factory">
+<code>row_factory</code> </dt> <dd>
+<p>The initial <a class="reference internal" href="#sqlite3.Cursor.row_factory" title="sqlite3.Cursor.row_factory"><code>row_factory</code></a> for <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> objects created from this connection. Assigning to this attribute does not affect the <code>row_factory</code> of existing cursors belonging to this connection, only new ones. Is <code>None</code> by default, meaning each row is returned as a <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a>.</p> <p>See <a class="reference internal" href="#sqlite3-howto-row-factory"><span class="std std-ref">How to create and use row factories</span></a> for more details.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Connection.text_factory">
+<code>text_factory</code> </dt> <dd>
+<p>A <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> that accepts a <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> parameter and returns a text representation of it. The callable is invoked for SQLite values with the <code>TEXT</code> data type. By default, this attribute is set to <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>.</p> <p>See <a class="reference internal" href="#sqlite3-howto-encoding"><span class="std std-ref">How to handle non-UTF-8 text encodings</span></a> for more details.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Connection.total_changes">
+<code>total_changes</code> </dt> <dd>
+<p>Return the total number of database rows that have been modified, inserted, or deleted since the database connection was opened.</p> </dd>
+</dl> </dd>
+</dl> </section> <section id="cursor-objects"> <span id="sqlite3-cursor-objects"></span><h3>Cursor objects</h3> <p>A <code>Cursor</code> object represents a <a class="reference external" href="https://en.wikipedia.org/wiki/Cursor_(databases)">database cursor</a> which is used to execute SQL statements, and manage the context of a fetch operation. Cursors are created using <a class="reference internal" href="#sqlite3.Connection.cursor" title="sqlite3.Connection.cursor"><code>Connection.cursor()</code></a>, or by using any of the <a class="reference internal" href="#sqlite3-connection-shortcuts"><span class="std std-ref">connection shortcut methods</span></a>.</p> <p>Cursor objects are <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterators</span></a>, meaning that if you <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>execute()</code></a> a <code>SELECT</code> query, you can simply iterate over the cursor to fetch the resulting rows:</p> <pre data-language="python">for row in cur.execute("SELECT t FROM data"):
+ print(row)
+</pre> <dl class="py class"> <dt class="sig sig-object py" id="sqlite3.Cursor">
+<code>class sqlite3.Cursor</code> </dt> <dd>
+<p>A <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> instance has the following attributes and methods.</p> <span class="target" id="index-6"></span><span class="target" id="index-7"></span><dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Cursor.execute">
+<code>execute(sql, parameters=(), /)</code> </dt> <dd>
+<p>Execute a single SQL statement, optionally binding Python values using <a class="reference internal" href="#sqlite3-placeholders"><span class="std std-ref">placeholders</span></a>.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>sql</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – A single SQL statement.</li> <li>
+<strong>parameters</strong> (<a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> | <a class="reference internal" href="../glossary#term-sequence"><span class="xref std std-term">sequence</span></a>) – Python values to bind to placeholders in <em>sql</em>. A <code>dict</code> if named placeholders are used. A <span class="xref std std-term">sequence</span> if unnamed placeholders are used. See <a class="reference internal" href="#sqlite3-placeholders"><span class="std std-ref">How to use placeholders to bind values in SQL queries</span></a>.</li> </ul> </dd> <dt class="field-even">Raises</dt> <dd class="field-even">
+<p><a class="reference internal" href="#sqlite3.ProgrammingError" title="sqlite3.ProgrammingError"><strong>ProgrammingError</strong></a> – If <em>sql</em> contains more than one SQL statement.</p> </dd> </dl> <p>If <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> is <a class="reference internal" href="#sqlite3.LEGACY_TRANSACTION_CONTROL" title="sqlite3.LEGACY_TRANSACTION_CONTROL"><code>LEGACY_TRANSACTION_CONTROL</code></a>, <a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code>isolation_level</code></a> is not <code>None</code>, <em>sql</em> is an <code>INSERT</code>, <code>UPDATE</code>, <code>DELETE</code>, or <code>REPLACE</code> statement, and there is no open transaction, a transaction is implicitly opened before executing <em>sql</em>.</p> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.12, will be removed in version 3.14: </span><a class="reference internal" href="exceptions#DeprecationWarning" title="DeprecationWarning"><code>DeprecationWarning</code></a> is emitted if <a class="reference internal" href="#sqlite3-placeholders"><span class="std std-ref">named placeholders</span></a> are used and <em>parameters</em> is a sequence instead of a <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>. Starting with Python 3.14, <a class="reference internal" href="#sqlite3.ProgrammingError" title="sqlite3.ProgrammingError"><code>ProgrammingError</code></a> will be raised instead.</p> </div> <p>Use <a class="reference internal" href="#sqlite3.Cursor.executescript" title="sqlite3.Cursor.executescript"><code>executescript()</code></a> to execute multiple SQL statements.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Cursor.executemany">
+<code>executemany(sql, parameters, /)</code> </dt> <dd>
+<p>For every item in <em>parameters</em>, repeatedly execute the <a class="reference internal" href="#sqlite3-placeholders"><span class="std std-ref">parameterized</span></a> <abbr title="Data Manipulation Language">DML</abbr> SQL statement <em>sql</em>.</p> <p>Uses the same implicit transaction handling as <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>execute()</code></a>.</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd">
+<ul class="simple"> <li>
+<strong>sql</strong> (<a class="reference internal" href="stdtypes#str" title="str">str</a>) – A single SQL DML statement.</li> <li>
+<strong>parameters</strong> (<a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a>) – An <span class="xref std std-term">iterable</span> of parameters to bind with the placeholders in <em>sql</em>. See <a class="reference internal" href="#sqlite3-placeholders"><span class="std std-ref">How to use placeholders to bind values in SQL queries</span></a>.</li> </ul> </dd> <dt class="field-even">Raises</dt> <dd class="field-even">
+<p><a class="reference internal" href="#sqlite3.ProgrammingError" title="sqlite3.ProgrammingError"><strong>ProgrammingError</strong></a> – If <em>sql</em> contains more than one SQL statement, or is not a DML statement.</p> </dd> </dl> <p>Example:</p> <pre data-language="python">rows = [
+ ("row1",),
+ ("row2",),
+]
+# cur is an sqlite3.Cursor object
+cur.executemany("INSERT INTO data VALUES(?)", rows)
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Any resulting rows are discarded, including DML statements with <a class="reference external" href="https://www.sqlite.org/lang_returning.html">RETURNING clauses</a>.</p> </div> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.12, will be removed in version 3.14: </span><a class="reference internal" href="exceptions#DeprecationWarning" title="DeprecationWarning"><code>DeprecationWarning</code></a> is emitted if <a class="reference internal" href="#sqlite3-placeholders"><span class="std std-ref">named placeholders</span></a> are used and the items in <em>parameters</em> are sequences instead of <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>s. Starting with Python 3.14, <a class="reference internal" href="#sqlite3.ProgrammingError" title="sqlite3.ProgrammingError"><code>ProgrammingError</code></a> will be raised instead.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Cursor.executescript">
+<code>executescript(sql_script, /)</code> </dt> <dd>
+<p>Execute the SQL statements in <em>sql_script</em>. If the <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> is <a class="reference internal" href="#sqlite3.LEGACY_TRANSACTION_CONTROL" title="sqlite3.LEGACY_TRANSACTION_CONTROL"><code>LEGACY_TRANSACTION_CONTROL</code></a> and there is a pending transaction, an implicit <code>COMMIT</code> statement is executed first. No other implicit transaction control is performed; any transaction control must be added to <em>sql_script</em>.</p> <p><em>sql_script</em> must be a <a class="reference internal" href="stdtypes#str" title="str"><code>string</code></a>.</p> <p>Example:</p> <pre data-language="python"># cur is an sqlite3.Cursor object
+cur.executescript("""
+ BEGIN;
+ CREATE TABLE person(firstname, lastname, age);
+ CREATE TABLE book(title, author, published);
+ CREATE TABLE publisher(name, address);
+ COMMIT;
+""")
+</pre> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Cursor.fetchone">
+<code>fetchone()</code> </dt> <dd>
+<p>If <a class="reference internal" href="#sqlite3.Cursor.row_factory" title="sqlite3.Cursor.row_factory"><code>row_factory</code></a> is <code>None</code>, return the next row query result set as a <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a>. Else, pass it to the row factory and return its result. Return <code>None</code> if no more data is available.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Cursor.fetchmany">
+<code>fetchmany(size=cursor.arraysize)</code> </dt> <dd>
+<p>Return the next set of rows of a query result as a <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>. Return an empty list if no more rows are available.</p> <p>The number of rows to fetch per call is specified by the <em>size</em> parameter. If <em>size</em> is not given, <a class="reference internal" href="#sqlite3.Cursor.arraysize" title="sqlite3.Cursor.arraysize"><code>arraysize</code></a> determines the number of rows to be fetched. If fewer than <em>size</em> rows are available, as many rows as are available are returned.</p> <p>Note there are performance considerations involved with the <em>size</em> parameter. For optimal performance, it is usually best to use the arraysize attribute. If the <em>size</em> parameter is used, then it is best for it to retain the same value from one <a class="reference internal" href="#sqlite3.Cursor.fetchmany" title="sqlite3.Cursor.fetchmany"><code>fetchmany()</code></a> call to the next.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Cursor.fetchall">
+<code>fetchall()</code> </dt> <dd>
+<p>Return all (remaining) rows of a query result as a <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>. Return an empty list if no rows are available. Note that the <a class="reference internal" href="#sqlite3.Cursor.arraysize" title="sqlite3.Cursor.arraysize"><code>arraysize</code></a> attribute can affect the performance of this operation.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Cursor.close">
+<code>close()</code> </dt> <dd>
+<p>Close the cursor now (rather than whenever <code>__del__</code> is called).</p> <p>The cursor will be unusable from this point forward; a <a class="reference internal" href="#sqlite3.ProgrammingError" title="sqlite3.ProgrammingError"><code>ProgrammingError</code></a> exception will be raised if any operation is attempted with the cursor.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Cursor.setinputsizes">
+<code>setinputsizes(sizes, /)</code> </dt> <dd>
+<p>Required by the DB-API. Does nothing in <code>sqlite3</code>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Cursor.setoutputsize">
+<code>setoutputsize(size, column=None, /)</code> </dt> <dd>
+<p>Required by the DB-API. Does nothing in <code>sqlite3</code>.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Cursor.arraysize">
+<code>arraysize</code> </dt> <dd>
+<p>Read/write attribute that controls the number of rows returned by <a class="reference internal" href="#sqlite3.Cursor.fetchmany" title="sqlite3.Cursor.fetchmany"><code>fetchmany()</code></a>. The default value is 1 which means a single row would be fetched per call.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Cursor.connection">
+<code>connection</code> </dt> <dd>
+<p>Read-only attribute that provides the SQLite database <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> belonging to the cursor. A <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> object created by calling <a class="reference internal" href="#sqlite3.Connection.cursor" title="sqlite3.Connection.cursor"><code>con.cursor()</code></a> will have a <a class="reference internal" href="#sqlite3.Cursor.connection" title="sqlite3.Cursor.connection"><code>connection</code></a> attribute that refers to <em>con</em>:</p> <pre data-language="pycon3">&gt;&gt;&gt; con = sqlite3.connect(":memory:")
+&gt;&gt;&gt; cur = con.cursor()
+&gt;&gt;&gt; cur.connection == con
+True
+</pre> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Cursor.description">
+<code>description</code> </dt> <dd>
+<p>Read-only attribute that provides the column names of the last query. To remain compatible with the Python DB API, it returns a 7-tuple for each column where the last six items of each tuple are <code>None</code>.</p> <p>It is set for <code>SELECT</code> statements without any matching rows as well.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Cursor.lastrowid">
+<code>lastrowid</code> </dt> <dd>
+<p>Read-only attribute that provides the row id of the last inserted row. It is only updated after successful <code>INSERT</code> or <code>REPLACE</code> statements using the <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>execute()</code></a> method. For other statements, after <a class="reference internal" href="#sqlite3.Cursor.executemany" title="sqlite3.Cursor.executemany"><code>executemany()</code></a> or <a class="reference internal" href="#sqlite3.Cursor.executescript" title="sqlite3.Cursor.executescript"><code>executescript()</code></a>, or if the insertion failed, the value of <code>lastrowid</code> is left unchanged. The initial value of <code>lastrowid</code> is <code>None</code>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Inserts into <code>WITHOUT ROWID</code> tables are not recorded.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Added support for the <code>REPLACE</code> statement.</p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Cursor.rowcount">
+<code>rowcount</code> </dt> <dd>
+<p>Read-only attribute that provides the number of modified rows for <code>INSERT</code>, <code>UPDATE</code>, <code>DELETE</code>, and <code>REPLACE</code> statements; is <code>-1</code> for other statements, including <abbr title="Common Table Expression">CTE</abbr> queries. It is only updated by the <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>execute()</code></a> and <a class="reference internal" href="#sqlite3.Cursor.executemany" title="sqlite3.Cursor.executemany"><code>executemany()</code></a> methods, after the statement has run to completion. This means that any resulting rows must be fetched in order for <code>rowcount</code> to be updated.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Cursor.row_factory">
+<code>row_factory</code> </dt> <dd>
+<p>Control how a row fetched from this <code>Cursor</code> is represented. If <code>None</code>, a row is represented as a <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a>. Can be set to the included <a class="reference internal" href="#sqlite3.Row" title="sqlite3.Row"><code>sqlite3.Row</code></a>; or a <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> that accepts two arguments, a <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> object and the <code>tuple</code> of row values, and returns a custom object representing an SQLite row.</p> <p>Defaults to what <a class="reference internal" href="#sqlite3.Connection.row_factory" title="sqlite3.Connection.row_factory"><code>Connection.row_factory</code></a> was set to when the <code>Cursor</code> was created. Assigning to this attribute does not affect <a class="reference internal" href="#sqlite3.Connection.row_factory" title="sqlite3.Connection.row_factory"><code>Connection.row_factory</code></a> of the parent connection.</p> <p>See <a class="reference internal" href="#sqlite3-howto-row-factory"><span class="std std-ref">How to create and use row factories</span></a> for more details.</p> </dd>
+</dl> </dd>
+</dl> </section> <section id="row-objects"> <span id="sqlite3-row-objects"></span><span id="sqlite3-columns-by-name"></span><h3>Row objects</h3> <dl class="py class"> <dt class="sig sig-object py" id="sqlite3.Row">
+<code>class sqlite3.Row</code> </dt> <dd>
+<p>A <code>Row</code> instance serves as a highly optimized <a class="reference internal" href="#sqlite3.Connection.row_factory" title="sqlite3.Connection.row_factory"><code>row_factory</code></a> for <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> objects. It supports iteration, equality testing, <a class="reference internal" href="functions#len" title="len"><code>len()</code></a>, and <a class="reference internal" href="../glossary#term-mapping"><span class="xref std std-term">mapping</span></a> access by column name and index.</p> <p>Two <code>Row</code> objects compare equal if they have identical column names and values.</p> <p>See <a class="reference internal" href="#sqlite3-howto-row-factory"><span class="std std-ref">How to create and use row factories</span></a> for more details.</p> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Row.keys">
+<code>keys()</code> </dt> <dd>
+<p>Return a <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> of column names as <a class="reference internal" href="stdtypes#str" title="str"><code>strings</code></a>. Immediately after a query, it is the first member of each tuple in <a class="reference internal" href="#sqlite3.Cursor.description" title="sqlite3.Cursor.description"><code>Cursor.description</code></a>.</p> </dd>
+</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Added support of slicing.</p> </div> </dd>
+</dl> </section> <section id="blob-objects"> <span id="sqlite3-blob-objects"></span><h3>Blob objects</h3> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> <dl class="py class"> <dt class="sig sig-object py" id="sqlite3.Blob">
+<code>class sqlite3.Blob</code> </dt> <dd>
+<p>A <a class="reference internal" href="#sqlite3.Blob" title="sqlite3.Blob"><code>Blob</code></a> instance is a <a class="reference internal" href="../glossary#term-file-like-object"><span class="xref std std-term">file-like object</span></a> that can read and write data in an SQLite <abbr title="Binary Large OBject">BLOB</abbr>. Call <a class="reference internal" href="functions#len" title="len"><code>len(blob)</code></a> to get the size (number of bytes) of the blob. Use indices and <a class="reference internal" href="../glossary#term-slice"><span class="xref std std-term">slices</span></a> for direct access to the blob data.</p> <p>Use the <a class="reference internal" href="#sqlite3.Blob" title="sqlite3.Blob"><code>Blob</code></a> as a <a class="reference internal" href="../glossary#term-context-manager"><span class="xref std std-term">context manager</span></a> to ensure that the blob handle is closed after use.</p> <pre data-language="python">con = sqlite3.connect(":memory:")
+con.execute("CREATE TABLE test(blob_col blob)")
+con.execute("INSERT INTO test(blob_col) VALUES(zeroblob(13))")
+
+# Write to our blob, using two write operations:
+with con.blobopen("test", "blob_col", 1) as blob:
+ blob.write(b"hello, ")
+ blob.write(b"world.")
+ # Modify the first and last bytes of our blob
+ blob[0] = ord("H")
+ blob[-1] = ord("!")
+
+# Read the contents of our blob
+with con.blobopen("test", "blob_col", 1) as blob:
+ greeting = blob.read()
+
+print(greeting) # outputs "b'Hello, world!'"
+</pre> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Blob.close">
+<code>close()</code> </dt> <dd>
+<p>Close the blob.</p> <p>The blob will be unusable from this point onward. An <a class="reference internal" href="#sqlite3.Error" title="sqlite3.Error"><code>Error</code></a> (or subclass) exception will be raised if any further operation is attempted with the blob.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Blob.read">
+<code>read(length=- 1, /)</code> </dt> <dd>
+<p>Read <em>length</em> bytes of data from the blob at the current offset position. If the end of the blob is reached, the data up to <abbr title="End of File">EOF</abbr> will be returned. When <em>length</em> is not specified, or is negative, <a class="reference internal" href="#sqlite3.Blob.read" title="sqlite3.Blob.read"><code>read()</code></a> will read until the end of the blob.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Blob.write">
+<code>write(data, /)</code> </dt> <dd>
+<p>Write <em>data</em> to the blob at the current offset. This function cannot change the blob length. Writing beyond the end of the blob will raise <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Blob.tell">
+<code>tell()</code> </dt> <dd>
+<p>Return the current access position of the blob.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="sqlite3.Blob.seek">
+<code>seek(offset, origin=os.SEEK_SET, /)</code> </dt> <dd>
+<p>Set the current access position of the blob to <em>offset</em>. The <em>origin</em> argument defaults to <a class="reference internal" href="os#os.SEEK_SET" title="os.SEEK_SET"><code>os.SEEK_SET</code></a> (absolute blob positioning). Other values for <em>origin</em> are <a class="reference internal" href="os#os.SEEK_CUR" title="os.SEEK_CUR"><code>os.SEEK_CUR</code></a> (seek relative to the current position) and <a class="reference internal" href="os#os.SEEK_END" title="os.SEEK_END"><code>os.SEEK_END</code></a> (seek relative to the blob’s end).</p> </dd>
+</dl> </dd>
+</dl> </section> <section id="prepareprotocol-objects"> <h3>PrepareProtocol objects</h3> <dl class="py class"> <dt class="sig sig-object py" id="sqlite3.PrepareProtocol">
+<code>class sqlite3.PrepareProtocol</code> </dt> <dd>
+<p>The PrepareProtocol type’s single purpose is to act as a <span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-0246/"><strong>PEP 246</strong></a> style adaption protocol for objects that can <a class="reference internal" href="#sqlite3-conform"><span class="std std-ref">adapt themselves</span></a> to <a class="reference internal" href="#sqlite3-types"><span class="std std-ref">native SQLite types</span></a>.</p> </dd>
+</dl> </section> <section id="exceptions"> <span id="sqlite3-exceptions"></span><h3>Exceptions</h3> <p>The exception hierarchy is defined by the DB-API 2.0 (<span class="target" id="index-9"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a>).</p> <dl class="py exception"> <dt class="sig sig-object py" id="sqlite3.Warning">
+<code>exception sqlite3.Warning</code> </dt> <dd>
+<p>This exception is not currently raised by the <code>sqlite3</code> module, but may be raised by applications using <code>sqlite3</code>, for example if a user-defined function truncates data while inserting. <code>Warning</code> is a subclass of <a class="reference internal" href="exceptions#Exception" title="Exception"><code>Exception</code></a>.</p> </dd>
+</dl> <dl class="py exception"> <dt class="sig sig-object py" id="sqlite3.Error">
+<code>exception sqlite3.Error</code> </dt> <dd>
+<p>The base class of the other exceptions in this module. Use this to catch all errors with one single <a class="reference internal" href="../reference/compound_stmts#except"><code>except</code></a> statement. <code>Error</code> is a subclass of <a class="reference internal" href="exceptions#Exception" title="Exception"><code>Exception</code></a>.</p> <p>If the exception originated from within the SQLite library, the following two attributes are added to the exception:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Error.sqlite_errorcode">
+<code>sqlite_errorcode</code> </dt> <dd>
+<p>The numeric error code from the <a class="reference external" href="https://sqlite.org/rescode.html">SQLite API</a></p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="sqlite3.Error.sqlite_errorname">
+<code>sqlite_errorname</code> </dt> <dd>
+<p>The symbolic name of the numeric error code from the <a class="reference external" href="https://sqlite.org/rescode.html">SQLite API</a></p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> </dd>
+</dl> <dl class="py exception"> <dt class="sig sig-object py" id="sqlite3.InterfaceError">
+<code>exception sqlite3.InterfaceError</code> </dt> <dd>
+<p>Exception raised for misuse of the low-level SQLite C API. In other words, if this exception is raised, it probably indicates a bug in the <code>sqlite3</code> module. <code>InterfaceError</code> is a subclass of <a class="reference internal" href="#sqlite3.Error" title="sqlite3.Error"><code>Error</code></a>.</p> </dd>
+</dl> <dl class="py exception"> <dt class="sig sig-object py" id="sqlite3.DatabaseError">
+<code>exception sqlite3.DatabaseError</code> </dt> <dd>
+<p>Exception raised for errors that are related to the database. This serves as the base exception for several types of database errors. It is only raised implicitly through the specialised subclasses. <code>DatabaseError</code> is a subclass of <a class="reference internal" href="#sqlite3.Error" title="sqlite3.Error"><code>Error</code></a>.</p> </dd>
+</dl> <dl class="py exception"> <dt class="sig sig-object py" id="sqlite3.DataError">
+<code>exception sqlite3.DataError</code> </dt> <dd>
+<p>Exception raised for errors caused by problems with the processed data, like numeric values out of range, and strings which are too long. <code>DataError</code> is a subclass of <a class="reference internal" href="#sqlite3.DatabaseError" title="sqlite3.DatabaseError"><code>DatabaseError</code></a>.</p> </dd>
+</dl> <dl class="py exception"> <dt class="sig sig-object py" id="sqlite3.OperationalError">
+<code>exception sqlite3.OperationalError</code> </dt> <dd>
+<p>Exception raised for errors that are related to the database’s operation, and not necessarily under the control of the programmer. For example, the database path is not found, or a transaction could not be processed. <code>OperationalError</code> is a subclass of <a class="reference internal" href="#sqlite3.DatabaseError" title="sqlite3.DatabaseError"><code>DatabaseError</code></a>.</p> </dd>
+</dl> <dl class="py exception"> <dt class="sig sig-object py" id="sqlite3.IntegrityError">
+<code>exception sqlite3.IntegrityError</code> </dt> <dd>
+<p>Exception raised when the relational integrity of the database is affected, e.g. a foreign key check fails. It is a subclass of <a class="reference internal" href="#sqlite3.DatabaseError" title="sqlite3.DatabaseError"><code>DatabaseError</code></a>.</p> </dd>
+</dl> <dl class="py exception"> <dt class="sig sig-object py" id="sqlite3.InternalError">
+<code>exception sqlite3.InternalError</code> </dt> <dd>
+<p>Exception raised when SQLite encounters an internal error. If this is raised, it may indicate that there is a problem with the runtime SQLite library. <code>InternalError</code> is a subclass of <a class="reference internal" href="#sqlite3.DatabaseError" title="sqlite3.DatabaseError"><code>DatabaseError</code></a>.</p> </dd>
+</dl> <dl class="py exception"> <dt class="sig sig-object py" id="sqlite3.ProgrammingError">
+<code>exception sqlite3.ProgrammingError</code> </dt> <dd>
+<p>Exception raised for <code>sqlite3</code> API programming errors, for example supplying the wrong number of bindings to a query, or trying to operate on a closed <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a>. <code>ProgrammingError</code> is a subclass of <a class="reference internal" href="#sqlite3.DatabaseError" title="sqlite3.DatabaseError"><code>DatabaseError</code></a>.</p> </dd>
+</dl> <dl class="py exception"> <dt class="sig sig-object py" id="sqlite3.NotSupportedError">
+<code>exception sqlite3.NotSupportedError</code> </dt> <dd>
+<p>Exception raised in case a method or database API is not supported by the underlying SQLite library. For example, setting <em>deterministic</em> to <code>True</code> in <a class="reference internal" href="#sqlite3.Connection.create_function" title="sqlite3.Connection.create_function"><code>create_function()</code></a>, if the underlying SQLite library does not support deterministic functions. <code>NotSupportedError</code> is a subclass of <a class="reference internal" href="#sqlite3.DatabaseError" title="sqlite3.DatabaseError"><code>DatabaseError</code></a>.</p> </dd>
+</dl> </section> <section id="sqlite-and-python-types"> <span id="sqlite3-types"></span><h3>SQLite and Python types</h3> <p>SQLite natively supports the following types: <code>NULL</code>, <code>INTEGER</code>, <code>REAL</code>, <code>TEXT</code>, <code>BLOB</code>.</p> <p>The following Python types can thus be sent to SQLite without any problem:</p> <table class="docutils align-default"> <thead> <tr>
+<th class="head"><p>Python type</p></th> <th class="head"><p>SQLite type</p></th> </tr> </thead> <tr>
+<td><p><code>None</code></p></td> <td><p><code>NULL</code></p></td> </tr> <tr>
+<td><p><a class="reference internal" href="functions#int" title="int"><code>int</code></a></p></td> <td><p><code>INTEGER</code></p></td> </tr> <tr>
+<td><p><a class="reference internal" href="functions#float" title="float"><code>float</code></a></p></td> <td><p><code>REAL</code></p></td> </tr> <tr>
+<td><p><a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a></p></td> <td><p><code>TEXT</code></p></td> </tr> <tr>
+<td><p><a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a></p></td> <td><p><code>BLOB</code></p></td> </tr> </table> <p>This is how SQLite types are converted to Python types by default:</p> <table class="docutils align-default"> <thead> <tr>
+<th class="head"><p>SQLite type</p></th> <th class="head"><p>Python type</p></th> </tr> </thead> <tr>
+<td><p><code>NULL</code></p></td> <td><p><code>None</code></p></td> </tr> <tr>
+<td><p><code>INTEGER</code></p></td> <td><p><a class="reference internal" href="functions#int" title="int"><code>int</code></a></p></td> </tr> <tr>
+<td><p><code>REAL</code></p></td> <td><p><a class="reference internal" href="functions#float" title="float"><code>float</code></a></p></td> </tr> <tr>
+<td><p><code>TEXT</code></p></td> <td><p>depends on <a class="reference internal" href="#sqlite3.Connection.text_factory" title="sqlite3.Connection.text_factory"><code>text_factory</code></a>, <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> by default</p></td> </tr> <tr>
+<td><p><code>BLOB</code></p></td> <td><p><a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a></p></td> </tr> </table> <p>The type system of the <code>sqlite3</code> module is extensible in two ways: you can store additional Python types in an SQLite database via <a class="reference internal" href="#sqlite3-adapters"><span class="std std-ref">object adapters</span></a>, and you can let the <code>sqlite3</code> module convert SQLite types to Python types via <a class="reference internal" href="#sqlite3-converters"><span class="std std-ref">converters</span></a>.</p> </section> <section id="default-adapters-and-converters-deprecated"> <span id="sqlite3-default-converters"></span><h3>Default adapters and converters (deprecated)</h3> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The default adapters and converters are deprecated as of Python 3.12. Instead, use the <a class="reference internal" href="#sqlite3-adapter-converter-recipes"><span class="std std-ref">Adapter and converter recipes</span></a> and tailor them to your needs.</p> </div> <p>The deprecated default adapters and converters consist of:</p> <ul class="simple"> <li>An adapter for <a class="reference internal" href="datetime#datetime.date" title="datetime.date"><code>datetime.date</code></a> objects to <a class="reference internal" href="stdtypes#str" title="str"><code>strings</code></a> in <a class="reference external" href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> format.</li> <li>An adapter for <a class="reference internal" href="datetime#datetime.datetime" title="datetime.datetime"><code>datetime.datetime</code></a> objects to strings in ISO 8601 format.</li> <li>A converter for <a class="reference internal" href="#sqlite3-converters"><span class="std std-ref">declared</span></a> “date” types to <a class="reference internal" href="datetime#datetime.date" title="datetime.date"><code>datetime.date</code></a> objects.</li> <li>A converter for declared “timestamp” types to <a class="reference internal" href="datetime#datetime.datetime" title="datetime.datetime"><code>datetime.datetime</code></a> objects. Fractional parts will be truncated to 6 digits (microsecond precision).</li> </ul> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The default “timestamp” converter ignores UTC offsets in the database and always returns a naive <a class="reference internal" href="datetime#datetime.datetime" title="datetime.datetime"><code>datetime.datetime</code></a> object. To preserve UTC offsets in timestamps, either leave converters disabled, or register an offset-aware converter with <a class="reference internal" href="#sqlite3.register_converter" title="sqlite3.register_converter"><code>register_converter()</code></a>.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.12.</span></p> </div> </section> <section id="command-line-interface"> <span id="sqlite3-cli"></span><h3>Command-line interface</h3> <p>The <code>sqlite3</code> module can be invoked as a script, using the interpreter’s <a class="reference internal" href="../using/cmdline#cmdoption-m"><code>-m</code></a> switch, in order to provide a simple SQLite shell. The argument signature is as follows:</p> <pre data-language="python">python -m sqlite3 [-h] [-v] [filename] [sql]
+</pre> <p>Type <code>.quit</code> or CTRL-D to exit the shell.</p> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-python-m-sqlite3-h-v-filename-sql-h">
+<code>-h, --help</code> </dt> <dd>
+<p>Print CLI help.</p> </dd>
+</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-python-m-sqlite3-h-v-filename-sql-v">
+<code>-v, --version</code> </dt> <dd>
+<p>Print underlying SQLite library version.</p> </dd>
+</dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </section> </section> <section id="how-to-guides"> <span id="sqlite3-howtos"></span><h2>How-to guides</h2> <section id="how-to-use-placeholders-to-bind-values-in-sql-queries"> <span id="sqlite3-placeholders"></span><h3>How to use placeholders to bind values in SQL queries</h3> <p>SQL operations usually need to use values from Python variables. However, beware of using Python’s string operations to assemble queries, as they are vulnerable to <a class="reference external" href="https://en.wikipedia.org/wiki/SQL_injection">SQL injection attacks</a>. For example, an attacker can simply close the single quote and inject <code>OR TRUE</code> to select all rows:</p> <pre data-language="python">&gt;&gt;&gt; # Never do this -- insecure!
+&gt;&gt;&gt; symbol = input()
+' OR TRUE; --
+&gt;&gt;&gt; sql = "SELECT * FROM stocks WHERE symbol = '%s'" % symbol
+&gt;&gt;&gt; print(sql)
+SELECT * FROM stocks WHERE symbol = '' OR TRUE; --'
+&gt;&gt;&gt; cur.execute(sql)
+</pre> <p>Instead, use the DB-API’s parameter substitution. To insert a variable into a query string, use a placeholder in the string, and substitute the actual values into the query by providing them as a <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> of values to the second argument of the cursor’s <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>execute()</code></a> method.</p> <p>An SQL statement may use one of two kinds of placeholders: question marks (qmark style) or named placeholders (named style). For the qmark style, <em>parameters</em> must be a <a class="reference internal" href="../glossary#term-sequence"><span class="xref std std-term">sequence</span></a> whose length must match the number of placeholders, or a <a class="reference internal" href="#sqlite3.ProgrammingError" title="sqlite3.ProgrammingError"><code>ProgrammingError</code></a> is raised. For the named style, <em>parameters</em> must be an instance of a <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> (or a subclass), which must contain keys for all named parameters; any extra items are ignored. Here’s an example of both styles:</p> <pre data-language="python">con = sqlite3.connect(":memory:")
+cur = con.execute("CREATE TABLE lang(name, first_appeared)")
+
+# This is the named style used with executemany():
+data = (
+ {"name": "C", "year": 1972},
+ {"name": "Fortran", "year": 1957},
+ {"name": "Python", "year": 1991},
+ {"name": "Go", "year": 2009},
+)
+cur.executemany("INSERT INTO lang VALUES(:name, :year)", data)
+
+# This is the qmark style used in a SELECT query:
+params = (1972,)
+cur.execute("SELECT * FROM lang WHERE first_appeared = ?", params)
+print(cur.fetchall())
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p><span class="target" id="index-10"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a> numeric placeholders are <em>not</em> supported. If used, they will be interpreted as named placeholders.</p> </div> </section> <section id="how-to-adapt-custom-python-types-to-sqlite-values"> <span id="sqlite3-adapters"></span><h3>How to adapt custom Python types to SQLite values</h3> <p>SQLite supports only a limited set of data types natively. To store custom Python types in SQLite databases, <em>adapt</em> them to one of the <a class="reference internal" href="#sqlite3-types"><span class="std std-ref">Python types SQLite natively understands</span></a>.</p> <p>There are two ways to adapt Python objects to SQLite types: letting your object adapt itself, or using an <em>adapter callable</em>. The latter will take precedence above the former. For a library that exports a custom type, it may make sense to enable that type to adapt itself. As an application developer, it may make more sense to take direct control by registering custom adapter functions.</p> <section id="how-to-write-adaptable-objects"> <span id="sqlite3-conform"></span><h4>How to write adaptable objects</h4> <p>Suppose we have a <code>Point</code> class that represents a pair of coordinates, <code>x</code> and <code>y</code>, in a Cartesian coordinate system. The coordinate pair will be stored as a text string in the database, using a semicolon to separate the coordinates. This can be implemented by adding a <code>__conform__(self, protocol)</code> method which returns the adapted value. The object passed to <em>protocol</em> will be of type <a class="reference internal" href="#sqlite3.PrepareProtocol" title="sqlite3.PrepareProtocol"><code>PrepareProtocol</code></a>.</p> <pre data-language="python">class Point:
+ def __init__(self, x, y):
+ self.x, self.y = x, y
+
+ def __conform__(self, protocol):
+ if protocol is sqlite3.PrepareProtocol:
+ return f"{self.x};{self.y}"
+
+con = sqlite3.connect(":memory:")
+cur = con.cursor()
+
+cur.execute("SELECT ?", (Point(4.0, -3.2),))
+print(cur.fetchone()[0])
+</pre> </section> <section id="how-to-register-adapter-callables"> <h4>How to register adapter callables</h4> <p>The other possibility is to create a function that converts the Python object to an SQLite-compatible type. This function can then be registered using <a class="reference internal" href="#sqlite3.register_adapter" title="sqlite3.register_adapter"><code>register_adapter()</code></a>.</p> <pre data-language="python">class Point:
+ def __init__(self, x, y):
+ self.x, self.y = x, y
+
+def adapt_point(point):
+ return f"{point.x};{point.y}"
+
+sqlite3.register_adapter(Point, adapt_point)
+
+con = sqlite3.connect(":memory:")
+cur = con.cursor()
+
+cur.execute("SELECT ?", (Point(1.0, 2.5),))
+print(cur.fetchone()[0])
+</pre> </section> </section> <section id="how-to-convert-sqlite-values-to-custom-python-types"> <span id="sqlite3-converters"></span><h3>How to convert SQLite values to custom Python types</h3> <p>Writing an adapter lets you convert <em>from</em> custom Python types <em>to</em> SQLite values. To be able to convert <em>from</em> SQLite values <em>to</em> custom Python types, we use <em>converters</em>.</p> <p>Let’s go back to the <code>Point</code> class. We stored the x and y coordinates separated via semicolons as strings in SQLite.</p> <p>First, we’ll define a converter function that accepts the string as a parameter and constructs a <code>Point</code> object from it.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Converter functions are <strong>always</strong> passed a <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> object, no matter the underlying SQLite data type.</p> </div> <pre data-language="python">def convert_point(s):
+ x, y = map(float, s.split(b";"))
+ return Point(x, y)
+</pre> <p>We now need to tell <code>sqlite3</code> when it should convert a given SQLite value. This is done when connecting to a database, using the <em>detect_types</em> parameter of <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code>connect()</code></a>. There are three options:</p> <ul class="simple"> <li>Implicit: set <em>detect_types</em> to <a class="reference internal" href="#sqlite3.PARSE_DECLTYPES" title="sqlite3.PARSE_DECLTYPES"><code>PARSE_DECLTYPES</code></a>
+</li> <li>Explicit: set <em>detect_types</em> to <a class="reference internal" href="#sqlite3.PARSE_COLNAMES" title="sqlite3.PARSE_COLNAMES"><code>PARSE_COLNAMES</code></a>
+</li> <li>Both: set <em>detect_types</em> to <code>sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES</code>. Column names take precedence over declared types.</li> </ul> <p>The following example illustrates the implicit and explicit approaches:</p> <pre data-language="python">class Point:
+ def __init__(self, x, y):
+ self.x, self.y = x, y
+
+ def __repr__(self):
+ return f"Point({self.x}, {self.y})"
+
+def adapt_point(point):
+ return f"{point.x};{point.y}"
+
+def convert_point(s):
+ x, y = list(map(float, s.split(b";")))
+ return Point(x, y)
+
+# Register the adapter and converter
+sqlite3.register_adapter(Point, adapt_point)
+sqlite3.register_converter("point", convert_point)
+
+# 1) Parse using declared types
+p = Point(4.0, -3.2)
+con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
+cur = con.execute("CREATE TABLE test(p point)")
+
+cur.execute("INSERT INTO test(p) VALUES(?)", (p,))
+cur.execute("SELECT p FROM test")
+print("with declared types:", cur.fetchone()[0])
+cur.close()
+con.close()
+
+# 2) Parse using column names
+con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
+cur = con.execute("CREATE TABLE test(p)")
+
+cur.execute("INSERT INTO test(p) VALUES(?)", (p,))
+cur.execute('SELECT p AS "p [point]" FROM test')
+print("with column names:", cur.fetchone()[0])
+</pre> </section> <section id="adapter-and-converter-recipes"> <span id="sqlite3-adapter-converter-recipes"></span><h3>Adapter and converter recipes</h3> <p>This section shows recipes for common adapters and converters.</p> <pre data-language="python">import datetime
+import sqlite3
+
+def adapt_date_iso(val):
+ """Adapt datetime.date to ISO 8601 date."""
+ return val.isoformat()
+
+def adapt_datetime_iso(val):
+ """Adapt datetime.datetime to timezone-naive ISO 8601 date."""
+ return val.isoformat()
+
+def adapt_datetime_epoch(val):
+ """Adapt datetime.datetime to Unix timestamp."""
+ return int(val.timestamp())
+
+sqlite3.register_adapter(datetime.date, adapt_date_iso)
+sqlite3.register_adapter(datetime.datetime, adapt_datetime_iso)
+sqlite3.register_adapter(datetime.datetime, adapt_datetime_epoch)
+
+def convert_date(val):
+ """Convert ISO 8601 date to datetime.date object."""
+ return datetime.date.fromisoformat(val.decode())
+
+def convert_datetime(val):
+ """Convert ISO 8601 datetime to datetime.datetime object."""
+ return datetime.datetime.fromisoformat(val.decode())
+
+def convert_timestamp(val):
+ """Convert Unix epoch timestamp to datetime.datetime object."""
+ return datetime.datetime.fromtimestamp(int(val))
+
+sqlite3.register_converter("date", convert_date)
+sqlite3.register_converter("datetime", convert_datetime)
+sqlite3.register_converter("timestamp", convert_timestamp)
+</pre> </section> <section id="how-to-use-connection-shortcut-methods"> <span id="sqlite3-connection-shortcuts"></span><h3>How to use connection shortcut methods</h3> <p>Using the <a class="reference internal" href="#sqlite3.Connection.execute" title="sqlite3.Connection.execute"><code>execute()</code></a>, <a class="reference internal" href="#sqlite3.Connection.executemany" title="sqlite3.Connection.executemany"><code>executemany()</code></a>, and <a class="reference internal" href="#sqlite3.Connection.executescript" title="sqlite3.Connection.executescript"><code>executescript()</code></a> methods of the <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> class, your code can be written more concisely because you don’t have to create the (often superfluous) <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> objects explicitly. Instead, the <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> objects are created implicitly and these shortcut methods return the cursor objects. This way, you can execute a <code>SELECT</code> statement and iterate over it directly using only a single call on the <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> object.</p> <pre data-language="python"># Create and fill the table.
+con = sqlite3.connect(":memory:")
+con.execute("CREATE TABLE lang(name, first_appeared)")
+data = [
+ ("C++", 1985),
+ ("Objective-C", 1984),
+]
+con.executemany("INSERT INTO lang(name, first_appeared) VALUES(?, ?)", data)
+
+# Print the table contents
+for row in con.execute("SELECT name, first_appeared FROM lang"):
+ print(row)
+
+print("I just deleted", con.execute("DELETE FROM lang").rowcount, "rows")
+
+# close() is not a shortcut method and it's not called automatically;
+# the connection object should be closed manually
+con.close()
+</pre> </section> <section id="how-to-use-the-connection-context-manager"> <span id="sqlite3-connection-context-manager"></span><h3>How to use the connection context manager</h3> <p>A <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> object can be used as a context manager that automatically commits or rolls back open transactions when leaving the body of the context manager. If the body of the <a class="reference internal" href="../reference/compound_stmts#with"><code>with</code></a> statement finishes without exceptions, the transaction is committed. If this commit fails, or if the body of the <code>with</code> statement raises an uncaught exception, the transaction is rolled back. If <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> is <code>False</code>, a new transaction is implicitly opened after committing or rolling back.</p> <p>If there is no open transaction upon leaving the body of the <code>with</code> statement, or if <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> is <code>True</code>, the context manager does nothing.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The context manager neither implicitly opens a new transaction nor closes the connection. If you need a closing context manager, consider using <a class="reference internal" href="contextlib#contextlib.closing" title="contextlib.closing"><code>contextlib.closing()</code></a>.</p> </div> <pre data-language="python">con = sqlite3.connect(":memory:")
+con.execute("CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR UNIQUE)")
+
+# Successful, con.commit() is called automatically afterwards
+with con:
+ con.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))
+
+# con.rollback() is called after the with block finishes with an exception,
+# the exception is still raised and must be caught
+try:
+ with con:
+ con.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))
+except sqlite3.IntegrityError:
+ print("couldn't add Python twice")
+
+# Connection object used as context manager only commits or rollbacks transactions,
+# so the connection object should be closed manually
+con.close()
+</pre> </section> <section id="how-to-work-with-sqlite-uris"> <span id="sqlite3-uri-tricks"></span><h3>How to work with SQLite URIs</h3> <p>Some useful URI tricks include:</p> <ul class="simple"> <li>Open a database in read-only mode:</li> </ul> <pre data-language="pycon3">&gt;&gt;&gt; con = sqlite3.connect("file:tutorial.db?mode=ro", uri=True)
+&gt;&gt;&gt; con.execute("CREATE TABLE readonly(data)")
+Traceback (most recent call last):
+OperationalError: attempt to write a readonly database
+</pre> <ul class="simple"> <li>Do not implicitly create a new database file if it does not already exist; will raise <a class="reference internal" href="#sqlite3.OperationalError" title="sqlite3.OperationalError"><code>OperationalError</code></a> if unable to create a new file:</li> </ul> <pre data-language="pycon3">&gt;&gt;&gt; con = sqlite3.connect("file:nosuchdb.db?mode=rw", uri=True)
+Traceback (most recent call last):
+OperationalError: unable to open database file
+</pre> <ul class="simple"> <li>Create a shared named in-memory database:</li> </ul> <pre data-language="python">db = "file:mem1?mode=memory&amp;cache=shared"
+con1 = sqlite3.connect(db, uri=True)
+con2 = sqlite3.connect(db, uri=True)
+with con1:
+ con1.execute("CREATE TABLE shared(data)")
+ con1.execute("INSERT INTO shared VALUES(28)")
+res = con2.execute("SELECT data FROM shared")
+assert res.fetchone() == (28,)
+</pre> <p>More information about this feature, including a list of parameters, can be found in the <a class="reference external" href="https://www.sqlite.org/uri.html">SQLite URI documentation</a>.</p> </section> <section id="how-to-create-and-use-row-factories"> <span id="sqlite3-howto-row-factory"></span><h3>How to create and use row factories</h3> <p>By default, <code>sqlite3</code> represents each row as a <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a>. If a <code>tuple</code> does not suit your needs, you can use the <a class="reference internal" href="#sqlite3.Row" title="sqlite3.Row"><code>sqlite3.Row</code></a> class or a custom <a class="reference internal" href="#sqlite3.Cursor.row_factory" title="sqlite3.Cursor.row_factory"><code>row_factory</code></a>.</p> <p>While <code>row_factory</code> exists as an attribute both on the <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code>Cursor</code></a> and the <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a>, it is recommended to set <a class="reference internal" href="#sqlite3.Connection.row_factory" title="sqlite3.Connection.row_factory"><code>Connection.row_factory</code></a>, so all cursors created from the connection will use the same row factory.</p> <p><code>Row</code> provides indexed and case-insensitive named access to columns, with minimal memory overhead and performance impact over a <code>tuple</code>. To use <code>Row</code> as a row factory, assign it to the <code>row_factory</code> attribute:</p> <pre data-language="pycon3">&gt;&gt;&gt; con = sqlite3.connect(":memory:")
+&gt;&gt;&gt; con.row_factory = sqlite3.Row
+</pre> <p>Queries now return <code>Row</code> objects:</p> <pre data-language="pycon3">&gt;&gt;&gt; res = con.execute("SELECT 'Earth' AS name, 6378 AS radius")
+&gt;&gt;&gt; row = res.fetchone()
+&gt;&gt;&gt; row.keys()
+['name', 'radius']
+&gt;&gt;&gt; row[0] # Access by index.
+'Earth'
+&gt;&gt;&gt; row["name"] # Access by name.
+'Earth'
+&gt;&gt;&gt; row["RADIUS"] # Column names are case-insensitive.
+6378
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <code>FROM</code> clause can be omitted in the <code>SELECT</code> statement, as in the above example. In such cases, SQLite returns a single row with columns defined by expressions, e.g. literals, with the given aliases <code>expr AS alias</code>.</p> </div> <p>You can create a custom <a class="reference internal" href="#sqlite3.Cursor.row_factory" title="sqlite3.Cursor.row_factory"><code>row_factory</code></a> that returns each row as a <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>, with column names mapped to values:</p> <pre data-language="python">def dict_factory(cursor, row):
+ fields = [column[0] for column in cursor.description]
+ return {key: value for key, value in zip(fields, row)}
+</pre> <p>Using it, queries now return a <code>dict</code> instead of a <code>tuple</code>:</p> <pre data-language="pycon3">&gt;&gt;&gt; con = sqlite3.connect(":memory:")
+&gt;&gt;&gt; con.row_factory = dict_factory
+&gt;&gt;&gt; for row in con.execute("SELECT 1 AS a, 2 AS b"):
+... print(row)
+{'a': 1, 'b': 2}
+</pre> <p>The following row factory returns a <a class="reference internal" href="../glossary#term-named-tuple"><span class="xref std std-term">named tuple</span></a>:</p> <pre data-language="python">from collections import namedtuple
+
+def namedtuple_factory(cursor, row):
+ fields = [column[0] for column in cursor.description]
+ cls = namedtuple("Row", fields)
+ return cls._make(row)
+</pre> <p><code>namedtuple_factory()</code> can be used as follows:</p> <pre data-language="pycon3">&gt;&gt;&gt; con = sqlite3.connect(":memory:")
+&gt;&gt;&gt; con.row_factory = namedtuple_factory
+&gt;&gt;&gt; cur = con.execute("SELECT 1 AS a, 2 AS b")
+&gt;&gt;&gt; row = cur.fetchone()
+&gt;&gt;&gt; row
+Row(a=1, b=2)
+&gt;&gt;&gt; row[0] # Indexed access.
+1
+&gt;&gt;&gt; row.b # Attribute access.
+2
+</pre> <p>With some adjustments, the above recipe can be adapted to use a <a class="reference internal" href="dataclasses#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass</code></a>, or any other custom class, instead of a <a class="reference internal" href="collections#collections.namedtuple" title="collections.namedtuple"><code>namedtuple</code></a>.</p> </section> <section id="how-to-handle-non-utf-8-text-encodings"> <span id="sqlite3-howto-encoding"></span><h3>How to handle non-UTF-8 text encodings</h3> <p>By default, <code>sqlite3</code> uses <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> to adapt SQLite values with the <code>TEXT</code> data type. This works well for UTF-8 encoded text, but it might fail for other encodings and invalid UTF-8. You can use a custom <a class="reference internal" href="#sqlite3.Connection.text_factory" title="sqlite3.Connection.text_factory"><code>text_factory</code></a> to handle such cases.</p> <p>Because of SQLite’s <a class="reference external" href="https://www.sqlite.org/flextypegood.html">flexible typing</a>, it is not uncommon to encounter table columns with the <code>TEXT</code> data type containing non-UTF-8 encodings, or even arbitrary data. To demonstrate, let’s assume we have a database with ISO-8859-2 (Latin-2) encoded text, for example a table of Czech-English dictionary entries. Assuming we now have a <a class="reference internal" href="#sqlite3.Connection" title="sqlite3.Connection"><code>Connection</code></a> instance <code>con</code> connected to this database, we can decode the Latin-2 encoded text using this <a class="reference internal" href="#sqlite3.Connection.text_factory" title="sqlite3.Connection.text_factory"><code>text_factory</code></a>:</p> <pre data-language="python">con.text_factory = lambda data: str(data, encoding="latin2")
+</pre> <p>For invalid UTF-8 or arbitrary data in stored in <code>TEXT</code> table columns, you can use the following technique, borrowed from the <a class="reference internal" href="../howto/unicode#unicode-howto"><span class="std std-ref">Unicode HOWTO</span></a>:</p> <pre data-language="python">con.text_factory = lambda data: str(data, errors="surrogateescape")
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <code>sqlite3</code> module API does not support strings containing surrogates.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="../howto/unicode#unicode-howto"><span class="std std-ref">Unicode HOWTO</span></a></p> </div> </section> </section> <section id="explanation"> <span id="sqlite3-explanation"></span><h2>Explanation</h2> <section id="transaction-control"> <span id="sqlite3-controlling-transactions"></span><span id="sqlite3-transaction-control"></span><h3>Transaction control</h3> <p><code>sqlite3</code> offers multiple methods of controlling whether, when and how database transactions are opened and closed. <a class="reference internal" href="#sqlite3-transaction-control-autocommit"><span class="std std-ref">Transaction control via the autocommit attribute</span></a> is recommended, while <a class="reference internal" href="#sqlite3-transaction-control-isolation-level"><span class="std std-ref">Transaction control via the isolation_level attribute</span></a> retains the pre-Python 3.12 behaviour.</p> <section id="transaction-control-via-the-autocommit-attribute"> <span id="sqlite3-transaction-control-autocommit"></span><h4>Transaction control via the <code>autocommit</code> attribute</h4> <p>The recommended way of controlling transaction behaviour is through the <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>Connection.autocommit</code></a> attribute, which should preferably be set using the <em>autocommit</em> parameter of <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code>connect()</code></a>.</p> <p>It is suggested to set <em>autocommit</em> to <code>False</code>, which implies <span class="target" id="index-11"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a>-compliant transaction control. This means:</p> <ul class="simple"> <li>
+<code>sqlite3</code> ensures that a transaction is always open, so <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code>connect()</code></a>, <a class="reference internal" href="#sqlite3.Connection.commit" title="sqlite3.Connection.commit"><code>Connection.commit()</code></a>, and <a class="reference internal" href="#sqlite3.Connection.rollback" title="sqlite3.Connection.rollback"><code>Connection.rollback()</code></a> will implicitly open a new transaction (immediately after closing the pending one, for the latter two). <code>sqlite3</code> uses <code>BEGIN DEFERRED</code> statements when opening transactions.</li> <li>Transactions should be committed explicitly using <code>commit()</code>.</li> <li>Transactions should be rolled back explicitly using <code>rollback()</code>.</li> <li>An implicit rollback is performed if the database is <a class="reference internal" href="#sqlite3.Connection.close" title="sqlite3.Connection.close"><code>close()</code></a>-ed with pending changes.</li> </ul> <p>Set <em>autocommit</em> to <code>True</code> to enable SQLite’s <a class="reference external" href="https://www.sqlite.org/lang_transaction.html#implicit_versus_explicit_transactions">autocommit mode</a>. In this mode, <a class="reference internal" href="#sqlite3.Connection.commit" title="sqlite3.Connection.commit"><code>Connection.commit()</code></a> and <a class="reference internal" href="#sqlite3.Connection.rollback" title="sqlite3.Connection.rollback"><code>Connection.rollback()</code></a> have no effect. Note that SQLite’s autocommit mode is distinct from the <span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a>-compliant <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>Connection.autocommit</code></a> attribute; use <a class="reference internal" href="#sqlite3.Connection.in_transaction" title="sqlite3.Connection.in_transaction"><code>Connection.in_transaction</code></a> to query the low-level SQLite autocommit mode.</p> <p>Set <em>autocommit</em> to <a class="reference internal" href="#sqlite3.LEGACY_TRANSACTION_CONTROL" title="sqlite3.LEGACY_TRANSACTION_CONTROL"><code>LEGACY_TRANSACTION_CONTROL</code></a> to leave transaction control behaviour to the <a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code>Connection.isolation_level</code></a> attribute. See <a class="reference internal" href="#sqlite3-transaction-control-isolation-level"><span class="std std-ref">Transaction control via the isolation_level attribute</span></a> for more information.</p> </section> <section id="transaction-control-via-the-isolation-level-attribute"> <span id="sqlite3-transaction-control-isolation-level"></span><h4>Transaction control via the <code>isolation_level</code> attribute</h4> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The recommended way of controlling transactions is via the <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> attribute. See <a class="reference internal" href="#sqlite3-transaction-control-autocommit"><span class="std std-ref">Transaction control via the autocommit attribute</span></a>.</p> </div> <p>If <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>Connection.autocommit</code></a> is set to <a class="reference internal" href="#sqlite3.LEGACY_TRANSACTION_CONTROL" title="sqlite3.LEGACY_TRANSACTION_CONTROL"><code>LEGACY_TRANSACTION_CONTROL</code></a> (the default), transaction behaviour is controlled using the <a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code>Connection.isolation_level</code></a> attribute. Otherwise, <code>isolation_level</code> has no effect.</p> <p>If the connection attribute <a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code>isolation_level</code></a> is not <code>None</code>, new transactions are implicitly opened before <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code>execute()</code></a> and <a class="reference internal" href="#sqlite3.Cursor.executemany" title="sqlite3.Cursor.executemany"><code>executemany()</code></a> executes <code>INSERT</code>, <code>UPDATE</code>, <code>DELETE</code>, or <code>REPLACE</code> statements; for other statements, no implicit transaction handling is performed. Use the <a class="reference internal" href="#sqlite3.Connection.commit" title="sqlite3.Connection.commit"><code>commit()</code></a> and <a class="reference internal" href="#sqlite3.Connection.rollback" title="sqlite3.Connection.rollback"><code>rollback()</code></a> methods to respectively commit and roll back pending transactions. You can choose the underlying <a class="reference external" href="https://www.sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions">SQLite transaction behaviour</a> — that is, whether and what type of <code>BEGIN</code> statements <code>sqlite3</code> implicitly executes – via the <a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code>isolation_level</code></a> attribute.</p> <p>If <a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code>isolation_level</code></a> is set to <code>None</code>, no transactions are implicitly opened at all. This leaves the underlying SQLite library in <a class="reference external" href="https://www.sqlite.org/lang_transaction.html#implicit_versus_explicit_transactions">autocommit mode</a>, but also allows the user to perform their own transaction handling using explicit SQL statements. The underlying SQLite library autocommit mode can be queried using the <a class="reference internal" href="#sqlite3.Connection.in_transaction" title="sqlite3.Connection.in_transaction"><code>in_transaction</code></a> attribute.</p> <p>The <a class="reference internal" href="#sqlite3.Cursor.executescript" title="sqlite3.Cursor.executescript"><code>executescript()</code></a> method implicitly commits any pending transaction before execution of the given SQL script, regardless of the value of <a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code>isolation_level</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><code>sqlite3</code> used to implicitly commit an open transaction before DDL statements. This is no longer the case.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The recommended way of controlling transactions is now via the <a class="reference internal" href="#sqlite3.Connection.autocommit" title="sqlite3.Connection.autocommit"><code>autocommit</code></a> attribute.</p> </div> </section> </section> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/library/sqlite3.html" class="_attribution-link">https://docs.python.org/3.12/library/sqlite3.html</a>
+ </p>
+</div>