liveBook · Manning

SQL

As explained in The Quick Python Book, Fourth Edition

An SQL query is a statement written in SQL that requests, filters, combines, or modifies data in a database.

SQL statements create database structures, insert and update records, and retrieve selected rows. Python commonly sends these statements through a DB-API connection and cursor. section 23.1.1 section 23.2

import sqlite3
conn = sqlite3.connect("datafile.db")

A minimal sqlite3 connection opens a local database file without requiring a separate server. section 23.2

A typical Python workflow is:

  • Create a connection with sqlite3.connect and obtain a cursor from it. section 23.2
  • Run SQL with cursor.execute, then retrieve rows with fetchone, fetchmany, fetchall, or cursor iteration. section 23.2
  • Use ? placeholders with a tuple, or named parameters beginning with : and a dictionary, instead of constructing SQL strings. section 23.2
  • Commit changes explicitly and close the connection when finished. section 23.2

Create, query, and update records

cursor.execute("create table people (id integer primary key, name text, count integer)") cursor.execute("insert into people (name, count) values (?, ?)", ("Jill", 15)) conn.commit() result = cursor.execute("select * from people where name like :name", {"name": "bob"}) print(result.fetchall()) cursor.execute("update people set count=? where name=?", (20, "Jill")) conn.commit() section 23.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains practical execution, parameter binding, result retrieval, commits, and cleanup, but not SQL internals or advanced query design.
Examples
Uses a people table to demonstrate insertion, named and positional parameters, selection, filtering, iteration, and updating.
What it assumes
Assumes general Python programming knowledge while demonstrating database connections, cursors, queries, and result handling.
What you can do after
Operate/configure sqlite3 databases by executing parameterized SQL, reading results, committing changes, and closing connections.
How it connects
Connects SQL with Python DB-API, SQLite, cursors, transactions, PostgreSQL, and MySQL.

Also explained in

Compare how 25 books explain SQL →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.