liveBook · Manning

SQL

As explained in Python How-To

SQL is a standardized language for defining, querying, and modifying data in relational databases.

Need to persist and retrieve task data? SQL provides the statements used to create a table and query records in an SQLite database connected through Python’s built-in sqlite3 module. section 14.3.1 section 14.3.2

The database workflow centers on four operations:

@classmethod
def create_sqlite_database(cls):
    """Create the SQLite database
    """
    with sqlite3.connect(TaskierDBOption.DB_SQLITE.value) as con:
        cls.con = con                                              #1
        cursor = con.cursor()
        cursor.execute("CREATE TABLE task (task_id text, title text, 
 desc text, urgency integer, status integer, completion_note text);")

Creates an SQLite database connection, opens a cursor, and executes a CREATE TABLE statement for task fields. section 14.3.1

Filtering tasks with a SQL query

A task loader builds a SELECT statement that filters records by status and urgency. When content is supplied, LIKE adds substring matching across the completion note, description, and title. fetchall returns tuples, which are converted into Task objects. section 14.3.2

Listing 14.6 Loading data from the SQLite database
@classmethod
def load_tasks(cls, statuses: list[TaskStatus]=None, 
 urgencies: list[int]=None, content: str=""):
   """The docstring as before
   """
   tasks = list()
   if app_db == TaskierDBOption.DB_CSV.value:
       # csv-related code from listing 14.3
       pass
   else:
       with cls.con as con:
           if statuses is None:
               statuses = tuple(map(int, TaskStatus))
           else:
               statuses = tuple(statuses) * 2
           if urgencies is None:
               urgencies = tuple(range(1, 6))
           else:
               urgencies = tuple(urgencies) * 2
           sql_stmt = f"SELECT * FROM task WHERE status in {statuses} 
 and urgency in {urgencies}"
           if content:
               sql_stmt += f" and ((completion_note LIKE '%{content}%') 
 or (desc LIKE '%{content}%') or (title LIKE 
 '%{content}%'))"
           cursor = con.cursor()
           cursor.execute(sql_stmt)
           tasks_tuple = cursor.fetchall()
           tasks = [Task(*x) for x in tasks_tuple]
   return tasks

Shows the load_tasks implementation, including optional status, urgency, and content filters and conversion of retrieved rows into task instances. section 14.3.2

Figure 14.5 Common operations with an SQLite database: query, insert, update, and delete. Query retrieves records from the database, insert saves a new record to the database, update updates an existing record, and delete removes an existing record.
CH14_F05_Cui

Summarizes query, insert, update, and delete as the common operations performed with an SQLite database. section 14.3.1

How Python How-To covers it

How deep it goes
Explains table creation, cursors, SELECT filtering, LIKE, tuple handling, and fetchall, but does not detail SQL syntax broadly.
Examples
Uses a task table, CREATE TABLE, filtered SELECT queries, LIKE matching, and conversion of returned tuples into Task objects.
What you can do after
Apply it via Python’s sqlite3 module to create a task table and retrieve records using status, urgency, and content filters.
How it connects
Connects SQL with SQLite, database connections, cursors, SQL statements, and CRUD operations.

Also explained in

Compare how 25 books explain SQL →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.