liveBook · Manning

Database connection

As explained in Coding with AI

A database connection is an active communication link through which software accesses a database and submits operations.

A database connection is an active communication link through which software accesses a database and submits operations. In Python, sqlite3 can open the SQLite file, create a cursor, execute a query, retrieve rows, and close the connection. section 5.3.2

Connecting a questions application

A practical workflow starts with a precise request: connect directly to SQLite without SQLAlchemy, then place the connection logic in a Questions class. The resulting code opens data/questions.db, creates a cursor, executes a query, fetches rows, and closes the connection. A later Flask entry point creates a DatabaseConnection with a with statement, passes its cursor to Questions, fetches data, and renders index.html. section 5.3.2 section 5.3.5

from flask import Flask, render_template
from app.models.database_connection import DatabaseConnection
from app.models.questions import Questions

app = Flask(__name__)

@app.route('/')
def index():
    db_path = 'data/questions.db'
    # Call the function and store the returned data in a variable
    with DatabaseConnection(db_path) as cursor:
        questions = Questions(cursor)
        data = questions.fetch_data()
    # Return the HTML template for the index page
    return render_template('index.html', data=data)

if __name__ == "__main__":
    app.run(debug=True)

Shows the complete Flask route, including the SQLite path, context-managed DatabaseConnection, Questions cursor, fetched data, template rendering, and application startup. section 5.3.5

How Coding with AI covers it

How deep it goes
Demonstrates opening, querying, fetching, passing, and closing connections, but does not develop connection internals.
Examples
Uses data/questions.db, a users query, the Questions class, and a Flask route that renders fetched database data.
What it assumes
Assumes familiarity with Python classes, SQL queries, Flask routes, and templates while demonstrating direct SQLite access.
What you can do after
Build it from scratch with sqlite3, integrate the connection into a class, and supply fetched data to a Flask template.
How it connects
Links database connections with Python, sqlite3, SQLite, SQLAlchemy, cursors, Flask, and context managers.

Also explained in

Compare how 6 books explain database connection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Coding with AI. The section links point to the parts of the book it draws on.