Text of docs.python.org › uk › 3 › library › sqlite3.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

sqlite3 — DB-API 2.0 interface for SQLite databases — Python 3.15.2 documentation

Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Постійність даних » sqlite3 — DB-API 2.0 interface for SQLite databases | Theme | sqlite3 — DB-API 2.0 interface for SQLite databases ¶ Вихідний код: Lib/sqlite3/ SQLite — це бібліотека C, яка надає легку дискову базу даних, яка не потребує окремого серверного процесу та дозволяє отримувати доступ до бази даних за допомогою нестандартного варіанту мови запитів SQL.

Деякі програми можуть використовувати SQLite для внутрішнього зберігання даних. Також можна створити прототип програми за допомогою SQLite, а потім перенести код у більшу базу даних, таку як PostgreSQL або Oracle. The sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249 , and requires the third-party SQLite library.

This is an optional module . If it is missing from your copy of CPython, look for documentation from your distributor (that is, whoever provided Python to you). If you are the distributor, see Requirements for optional modules . Цей документ включає в себе 4 головні розділи: sqlite3-tutorial`вчить як використовувати :mod: !sqlite3` модуль. Посилання описує класи і функції, які визначає цей модуль How-to guides деталі як вирішувати певні задачі.

Пояснення надає поглиблений контекст контролю транзакцій. Дивись також https://www.sqlite.org Веб-сторінка SQLite; документація описує синтаксис і доступні типи даних для підтримуваного діалекту SQL. https://www.w3schools.com/sql/ Підручник, довідник і приклади для вивчення синтаксису SQL.

PEP 249 - Специфікація API бази даних 2.0 PEP, написаний Марком-Андре Лембургом. Підручник ¶ На цьому курсі Ви створите базу данних фільмів Монті Пайтон використовуючи базовий функціонал sqlite3 . Це передбачає фундаментальне розуміння концепту баз данних, включаючи cursors і transactions .

First, we need to create a new database and open a database connection to allow sqlite3 to work with it. Call sqlite3.connect() to create a connection to the database tutorial.db in the current working directory, implicitly creating it if it does not exist: import sqlite3 con = sqlite3 . connect ( "tutorial.db" ) Поверненний Connection об’єкт con відображає з’єднання з базою данних на диску.

Щоб виконувати SQL викази і отримувати результати із запитів SQL, нам знадобиться використовувати курсор бази даних. Викличте con.cursor() , щоб створити Cursor : cur = con . cursor () Now that we’ve got a database connection and a cursor, we can create a database table movie with columns for title, release year, and review score.

For simplicity, we can just use column names in the table declaration – thanks to the flexible typing feature of SQLite, specifying the data types is optional. Execute the CREATE TABLE statement by calling cur.execute(...) : cur . execute ( "CREATE TABLE movie(title, year, score)" ) We can verify that the new table has been created by querying the sqlite_master table built-in to SQLite, which should now contain an entry for the movie table definition (see The Schema Table for details).

Execute that query by calling cur.execute(...) , assign the result to res , and call res.fetchone() to fetch the resulting row: >>> res = cur . execute ( "SELECT name FROM sqlite_master" ) >>> res . fetchone () ('movie',) We can see that the table has been created, as the query returns a tuple containing the table’s name. If we query sqlite_master for a non-existent table spam , res.fetchone() will return None : >>> res = cur . execute ( "SELECT name FROM sqlite_master WHERE name='spam'" ) >>> res . fetchone () is None True Now, add two rows of data supplied as SQL literals by executing an INSERT statement, once again by calling cur.execute(...) : cur . execute ( """ INSERT INTO movie VALUES ('Monty Python and the Holy Grail', 1975, 8.2), ('And Now for Something Completely Different', 1971, 7.5) """ ) The INSERT statement implicitly opens a transaction, which needs to be committed before changes are saved in the database (see Transaction control for details).

Call con.commit() on the connection object to commit the transaction: con . commit () We can verify that the data was inserted correctly by executing a SELECT query. Use the now-familiar cur.execute(...) to assign the result to res , and call res.fetchall() to return all resulting rows: >>> res = cur . execute ( "SELECT score FROM movie" ) >>> res . fetchall () [(8.2,), (7.5,)] The result is a list of two tuple s, one per row, each containing that row’s score value.

Now, insert three more rows by calling cur.executemany(...) : 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. Notice that ? placeholders are used to bind data to the query.

Always use placeholders instead of string formatting to bind Python values to SQL statements, to avoid SQL injection attacks (see How to use placeholders to bind values in SQL queries for more details). We can verify that the new rows were inserted by executing a SELECT query, this time iterating over the results of the query: >>> 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") Each row is a two-item tuple of (year, title) , matching the columns selected in the query.

Finally, verify that the database has been written to disk by calling con.close() to close the existing connection, opening a new one, creating a new cursor, then querying the database: >>> con . close () >>> new_con = sqlite3 . connect ( "tutorial.db" ) >>> new_cur = new_con . cursor () >>> res = new_cur . execute ( "SELECT title, year FROM movie ORDER BY score DESC" ) >>> title , year = res . fetchone () >>> 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 >>> new_con . close () You’ve now created an SQLite database using the sqlite3 module, inserted data and retrieved values from it in multiple ways.

Дивись також How-to guides for further reading: How to use placeholders to bind values in SQL queries How to adapt custom Python types to SQLite values How to convert SQLite values to custom Python types How to use the connection context manager How to create and use row factories Пояснення for in-depth background on transaction control. Посилан�

The rest of this page is on the live site.