liveBook · Manning

SQLite

As explained in A Pythonic Adventure: From Python basics to a working web app

SQLite is an embedded relational database engine that stores a database in a self-contained file.

SQLite gives the order application a sturdier home than a JSON file: it keeps every order in its own database file, orders.db. Instead of loading and rewriting a whole list, the application connects to the database and asks it to store or retrieve records. section 12.0

A small SQLite workflow looks like this:

  • Connect to orders.db and create a cursor. section 12.0
  • Create the orders table if it does not already exist. section 12.0
  • Insert each new order, then call commit() so it is saved. section 12.0
  • Run SELECT queries and fetch rows when displaying saved orders. section 12.0

The order counter

When a customer chooses a drink, flavor, and topping, save_order() inserts those values into orders. A separate list route retrieves every row and displays the orders in a table. section 12.0

Listing 12. 3 app.py: Add orders to the table
. . .
from flask import Flask, render_template, request
 
def save_order(order):
    con = sqlite3.connect("orders.db")
    cur = con.cursor()
    cur.execute(
    "INSERT INTO orders(name,drink,flavor,topping) VALUES(?,?,?,?);",
    (order["name"], order["drink"], order["flavor"], order["topping"]),
    )
    con.commit()
    return
. . .

Inspect the compact Python function that connects to orders.db, inserts an order, and commits the change. section 12.0

How A Pythonic Adventure: From Python basics to a working web app covers it

How deep it goes
Explains connections, cursors, tables, inserts, commits, SELECT queries, and fetched rows through a working order application.
Examples
Uses an orders.db file, drink orders, an orders table, insertion, retrieval, and an HTML order list.
What it assumes
Assumes an existing JSON-based order application and introduces database storage as its replacement.
What you can do after
Operate SQLite through Python to persist new orders and retrieve them for display.
How it connects
Connects SQLite with SQL, JSON files, Python's sqlite3 module, and Flask routes.

Also explained in

Compare how 15 books explain SQLite →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of A Pythonic Adventure: From Python basics to a working web app. The section links point to the parts of the book it draws on.