添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
热心的楼梯  ·  创建关联表 - SQLModel - ...·  2 月前    · 
刚失恋的蚂蚁  ·  sql - Fastest Way ...·  3 周前    · 
大气的凳子  ·  Spark ...·  2 年前    · 
无邪的柑橘  ·  Oops!!! - 简书·  2 年前    · 
爱跑步的野马  ·  Problem with C++, I ...·  2 年前    · 

// Tutorial //

How To Use the sqlite3 Module in Python 3

Published on June 2, 2020 · Updated on June 2, 2020
Default avatar

By DavidMuller

Author of Intuitive Python

How To Use the sqlite3 Module in Python 3

The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

Introduction

SQLite is a self-contained, file-based SQL database. SQLite comes bundled with Python and can be used in any of your Python applications without having to install any additional software.

In this tutorial, we’ll go through the sqlite3 module in Python 3 . We’ll create a connection to a SQLite database, add a table to that database, insert data into that table, and read and modify data in that table.

For this tutorial, we’ll be working primarily with an inventory of fish that we need to modify as fish are added to or removed from a fictional aquarium.

Prerequisites

  • How to Code in Python3
  • An Introduction to Queries in MySQL
  • Step 1 — Creating a Connection to a SQLite Database

    Connection object that we will use to interact with the SQLite database held in the file aquarium.db. The aquarium.db file is created automatically by sqlite3.connect() if aquarium.db does not already exist on our computer.

    We can verify we successfully created our connection object by running:

    print(connection.total_changes)
    

    If we run this Python code, we will see output like:

    Output
    0

    connection.total_changes is the total number of database rows that have been changed by connection. Since we have not executed any SQL commands yet, 0 total_changes is correct.

    If, at any time, we find we want to start this tutorial again, we can delete the aquarium.db file from our computer.

    Note: It is also possible to connect to a SQLite database that resides strictly in memory (and not in a file) by passing the special string ":memory:" into sqlite3.connect(). For example, sqlite3.connect(":memory:"). A ":memory:" SQLite database will disappear as soon as your Python program exits. This might be convenient if you want a temporary sandbox to try something out in SQLite, and don’t need to persist any data after your program exits.

    Step 2 — Adding Data to the SQLite Database

    Cursor object. Cursor objects allow us to send SQL statements to a SQLite database using cursor.execute(). The "CREATE TABLE fish ..." string is a SQL statement that creates a table named fish with the three columns described earlier: name of type TEXT, species of type TEXT, and tank_number of type INTEGER.

    Now that we have created a table, we can insert rows of data into it:

    cursor.execute("INSERT INTO fish VALUES ('Sammy', 'shark', 1)")
    cursor.execute("INSERT INTO fish VALUES ('Jamie', 'cuttlefish', 7)")
    

    We call cursor.execute() two times: once to insert a row for the shark Sammy in tank 1, and once to insert a row for the cuttlefish Jamie in tank 7. "INSERT INTO fish VALUES ..." is a SQL statement that allows us to add rows to a table.

    In the next section, we will use a SQL SELECT statement to inspect the rows we just inserted into our fish table.

    Step 3 — Reading Data from the SQLite Database

    SQL injection attacks. SQL injection attacks can be used to steal, alter, or otherwise modify data stored in your database. Always use the ? placeholder in your SQL statements to dynamically substitute values from your Python program. Pass a tuple of values as the second argument to Cursor.execute() to bind your values to the SQL statement. This substitution pattern is demonstrated here and in other parts of this tutorial as well.

    Step 4 — Modifying Data in the SQLite Database

    Step 5 — Using with Statements For Automatic Cleanup

    Connection object named connection, and a Cursor object named cursor.

    In the same way that Python files should be closed when we are done working with them, Connection and Cursor objects should also be closed when they are no longer needed.

    We can use a with statement to help us automatically close Connection and Cursor objects:

    from contextlib import closing
    with closing(sqlite3.connect("aquarium.db")) as connection:
        with closing(connection.cursor()) as cursor:
            rows = cursor.execute("SELECT 1").fetchall()
            print(rows)
    

    closing is a convenience function provided by the contextlib module. When a with statement exits, closing ensures that close() is called on whatever object is passed to it. The closing function is used twice in this example. Once to ensure that the Connection object returned by sqlite3.connect() is automatically closed, and a second time to ensure that the Cursor object returned by connection.cursor() is automatically closed.

    If we run this code, we will see output like the following:

    Output
    [(1,)]

    Since "SELECT 1" is a SQL statement that always returns a single row with a single column with a value of 1, it makes sense to see a single tuple with 1 as its only value returned by our code.

    Conclusion

    contextlib.closing to automatically call close() on Python objects in with statements.

    From here we can learn more about SQL databases in SQLite vs MySQL vs PostgreSQL: A Comparison Of Relational Database Management Systems.

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Learn more about us


    About the authors
    Default avatar
    DavidMuller

    author

    Author of Intuitive Python

    Check out Intuitive Python: Productive Development for Projects that Last

    https://pragprog.com/titles/dmpython/intuitive-python/



    Still looking for an answer?

    Ask a question Search for more help

    Was this helpful?
    2 Comments
    

    This textbox defaults to using Markdown to format your answer.

    You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

    I see some tutorials show executing using the connections while others use cursor What is the difference ,