🐍 Python for Everyone

← Back to all chapters

Chapter 21 of 27 Intermediate 85 min read

Working with Databases

Chapter 13's CSV files work fine for small, flat, single-user data — but the moment multiple programs need to read and write the same data at once, or the data needs querying by more than "read the whole file into memory," a flat file stops being enough. A database is software built specifically to store, query, and update data reliably, even with many programs hitting it at once. This chapter covers the two dominant kinds — relational (MySQL) and document-based (MongoDB) — the real, production mysql-connector-python and pymongo APIs for talking to them from Python, why parameterized queries matter, and how the exact same code points at a cloud-hosted database instead of a local one.

How to read this chapter

Picture a school's student records stored in students.csv (Chapter 13). One program reads it, updates a grade, and writes the whole file back — fine, until a second program tries to do the same thing at the same moment and one of their changes silently disappears. A database solves exactly this: it lets many programs read and write the same data safely, query for exactly the rows or documents they need instead of loading everything into memory, and keeps that data intact even if a program crashes mid-update. This chapter is about how Python talks to one.
Sub-topic 1 of 8

1. What a database connection is, and why Python needs a driver

At a glance
  • A database is a separate piece of software (often running on its own server) that stores and manages data — Python talks to it over a network connection, even when it's running on the same machine.
  • A driver library (mysql-connector-python for MySQL, pymongo for MongoDB) is what actually speaks the database's specific network protocol on Python's behalf.
  • Both drivers share the same shape: connect, get an object to run commands through, run commands, read results back.
Why this matters: every tool in this chapter is really just one consistent pattern (connect → get a working object → run a command → read results) applied to two different kinds of database — seeing that shared shape up front makes the rest of the chapter feel like one idea, not two unrelated ones.
What is... a database? A database is software dedicated to storing, querying, and updating data reliably — handling many simultaneous readers and writers safely, enforcing rules about what data is allowed in, and surviving crashes without losing or corrupting data. It's a separate running program (a "server"), not a file Python opens directly the way Chapter 13's open() did — Python talks to it over a network connection instead, even when that database happens to be running on the very same computer.

Because a database is a separate program speaking its own protocol, Python needs a translator: a library that knows how to open that network connection, send commands in the format the database expects, and translate results back into ordinary Python values.

What is... a driver library? A driver (or "connector" or "client library") is a Python package written specifically to speak one database's network protocol. mysql-connector-python is the official driver for MySQL; pymongo is the official driver for MongoDB. Installing one (pip install mysql-connector-python or pip install pymongo, neither run in this course) is what makes import mysql.connector or import pymongo possible in a real project.
the shared shape, both drivers
MySQL (mysql-connector-python)      MongoDB (pymongo)
------------------------------      ------------------------------
connect()        -> connection      MongoClient()   -> client
connection.cursor() -> cursor       client[db_name] -> database
cursor.execute(sql, params)         database[collection_name] -> collection
cursor.fetchall()/.fetchone()       collection.find()/.find_one()
connection.commit()                 collection.insert_one(doc)

Every sub-topic from here on is filling in one row of that table with real detail — connecting, running a command, and reading results back, for each database in turn.

About the examples in this chapter: this course has no backend and cannot connect to a real MySQL or MongoDB server, and never commits credentials. Every example that actually runs uses a small FakeConnection/FakeCursor or FakeCollection class — a stand-in that mimics the real driver's method names and call shape closely enough to demonstrate the pattern, clearly commented as a stand-in every time it appears. Real, uncommented connection code is shown too (labeled "what this looks like against a real server"), so you learn the genuine API — it's just never executed here.
Go Deeper: why not just keep using CSV files for everything?

A CSV file has no built-in protection against two programs writing to it at the same time (the exact race Chapter 20 studied, just for a file instead of a shared variable), no way to ask "give me only the rows where grade > 90" without reading and scanning the entire file in Python, and no enforced structure (a script with a typo could easily append a row with the wrong number of columns). Databases exist specifically to solve those three problems at scale — safe concurrent access, efficient querying, and enforced (or deliberately flexible, for MongoDB) structure.

Quick recap
  • A database is separate software that stores and manages data reliably, reached over a network connection.
  • A driver library speaks that database's specific protocol on Python's behalf.
  • Every example that runs in this chapter uses a small Fake class standing in for the real driver, clearly labeled.
Sub-topic 2 of 8

2. Connecting to MySQL with mysql-connector-python

At a glance
  • mysql.connector.connect(host=..., user=..., password=..., database=...) opens a connection to a MySQL server.
  • connection.cursor() returns a cursor — the object every SQL command actually runs through.
  • This chapter's runnable examples use FakeConnection/FakeCursor, standing in for the real driver's objects.
Why this matters: connect() and .cursor() are the first two calls in literally every MySQL script — getting comfortable with exactly what each one returns is the foundation the rest of this chapter's MySQL sub-topics build on.

Here's what a real connection looks like against a real MySQL server — shown for reference, never executed in this course:

what_this_looks_like_for_real.py (reference only -- not run)
import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="app_user",
    password="a-real-password-would-go-here",
    database="school_records"
)
cursor = connection.cursor()
What is... a cursor? A cursor is the object a MySQL connection hands back that every SQL command actually runs through — calling cursor.execute(sql) sends a command to the database, and the cursor is also what reading results (fetchone(), fetchall()) happens through afterward. Think of the connection as the open phone line to the database, and the cursor as the actual conversation happening over it.

Since a real server isn't available here, every runnable MySQL example in this chapter uses FakeConnection and FakeCursor — small classes that store rows in an ordinary Python list and dict instead of talking to a real server, but expose the exact same method names (.cursor(), .execute(), .fetchall(), .commit()) a real connection and cursor would:

fake_mysql_setup.py
# FakeConnection/FakeCursor stand in for a real mysql.connector connection
# and cursor object, so this chapter's examples run without a live MySQL
# server. Same method names, same call shape as the real driver.

class FakeCursor:
    def __init__(self, table):
        self.table = table          # a list of dicts, standing in for SQL rows
        self._last_result = []

    def execute(self, sql, params=None):
        # A real cursor would send `sql` to the server; this fake one just
        # remembers what was asked for so fetch methods below can respond.
        self._last_sql = sql
        self._last_params = params or ()

    def fetchall(self):
        return list(self._last_result)

    def fetchone(self):
        return self._last_result[0] if self._last_result else None


class FakeConnection:
    def __init__(self, table):
        self.table = table

    def cursor(self):
        return FakeCursor(self.table)

    def commit(self):
        pass  # a real connection would save changes; nothing to save here


students_table = [
    {"id": 1, "name": "Ana Torres", "grade": 91},
    {"id": 2, "name": "Ben Osei", "grade": 78},
]
connection = FakeConnection(students_table)
cursor = connection.cursor()
print(type(cursor).__name__)
actual output of fake_mysql_setup.py
FakeCursor

connection.cursor() is real MySQL vocabulary — a real connection's .cursor() method returns a real cursor object the exact same way. The next sub-topic makes FakeCursor actually search students_table when .execute() is called, so it behaves like a genuine (if simplified) query engine.

Go Deeper: why does connect() take a whole database name, not just a server?

A single MySQL server commonly hosts many separate databases at once (a company might run one server with a school_records database and a completely separate inventory database side by side) — the database= argument tells connect() which one this particular connection should operate on, so table names in later queries don't need to be qualified with the database name every time.

Quick recap
  • mysql.connector.connect(host=, user=, password=, database=) opens a connection to a real MySQL server.
  • connection.cursor() returns a cursor, the object every SQL command runs through.
  • This chapter's runnable examples use FakeConnection/FakeCursor, matching the real driver's method names.
Sub-topic 3 of 8

3. Cursors, execute(), and parameterized queries

At a glance
  • cursor.execute(sql, params) runs a SQL command, with %s placeholders in sql filled in safely from the params tuple.
  • cursor.fetchall() returns every matching row; cursor.fetchone() returns just the first one (or None).
  • connection.commit() saves changes made by INSERT/UPDATE/DELETE permanently.
Why this matters: the %s-placeholder style used here isn't just a style choice — Sub-topic 4 shows exactly what goes wrong when a query is built without it, so understanding this pattern now is what makes that danger concrete rather than abstract.
What is... a parameterized query? A parameterized query writes %s as a placeholder inside the SQL string wherever a real value belongs, then passes the actual values separately, as a tuple, to cursor.execute(sql, params). The driver fills in each %s safely, treating the substituted value strictly as data — never as part of the SQL command itself, no matter what characters that value contains.
fake_mysql_query.py
# FakeCursor stands in for a real mysql.connector cursor -- same method
# names (execute, fetchall, fetchone) as the real driver, but it searches
# an in-memory list of dicts instead of sending SQL to a live server.

class FakeCursor:
    def __init__(self, table):
        self.table = table
        self._last_result = []

    def execute(self, sql, params=None):
        params = params or ()
        # This fake only understands one shape of query, just enough to
        # demonstrate the real cursor.execute(sql, params) call signature:
        # "SELECT * FROM students WHERE grade > %s"
        if "grade > %s" in sql:
            threshold = params[0]
            self._last_result = [row for row in self.table if row["grade"] > threshold]
        elif "id = %s" in sql:
            student_id = params[0]
            self._last_result = [row for row in self.table if row["id"] == student_id]
        else:
            self._last_result = list(self.table)

    def fetchall(self):
        return list(self._last_result)

    def fetchone(self):
        return self._last_result[0] if self._last_result else None


students_table = [
    {"id": 1, "name": "Ana Torres", "grade": 91},
    {"id": 2, "name": "Ben Osei", "grade": 78},
    {"id": 3, "name": "Chen Wu", "grade": 88},
]
cursor = FakeCursor(students_table)

cursor.execute("SELECT * FROM students WHERE grade > %s", (85,))
for row in cursor.fetchall():
    print(f"{row['name']}: {row['grade']}")

cursor.execute("SELECT * FROM students WHERE id = %s", (2,))
print(cursor.fetchone())
actual output of fake_mysql_query.py
Ana Torres: 91
Chen Wu: 88
{'id': 2, 'name': 'Ben Osei', 'grade': 78}

Notice the call shape: cursor.execute("... WHERE grade > %s", (85,)) — a real MySQL cursor uses this exact same signature, with %s placeholders in the SQL string and the actual values passed as a separate tuple, never glued directly into the string with an f-string. fetchall() returns every matching row as a list; fetchone() returns just the first one, or None if nothing matched.

What is... connection.commit()? For queries that change data (INSERT, UPDATE, DELETE), MySQL doesn't save those changes permanently until connection.commit() is called — this gives a program a chance to run several related changes and either commit them all together or back out if something goes wrong partway through, rather than each individual execute() call taking effect immediately and irreversibly.
try_it.py
Click "Run Code" — try changing the threshold from 90 to 80 and see which names print.
Go Deeper: what does %s actually stand for?

%s is mysql-connector-python's placeholder syntax regardless of what type of value is being substituted — a string, a number, a date — the driver figures out the correct way to safely represent whatever Python value is passed in that position. It looks similar to Chapter 6's old-style %-formatting for strings, but it's a different thing entirely: string formatting happens in Python before anything is sent anywhere, while a parameterized query's placeholder substitution happens inside the database driver itself, specifically so it can be done safely (Sub-topic 4 shows exactly why that distinction matters).

Quick recap
  • cursor.execute(sql, params) runs a query, with %s placeholders filled in safely from a separate params tuple.
  • fetchall() gets every matching row; fetchone() gets just the first, or None.
  • connection.commit() makes changes from INSERT/UPDATE/DELETE permanent.
Sub-topic 4 of 8

4. SQL injection, and why parameterized queries matter

At a glance
  • Building a SQL string with an f-string or + lets untrusted input change the meaning of the query, not just its data — this is a SQL injection attack.
  • Parameterized queries (%s + a separate params tuple) close this gap entirely, since substituted values are always treated as data, never as SQL syntax.
  • This is one of the most consequential security lessons in this entire course — real breaches have happened from exactly this mistake.
Why this matters: Sub-topic 3 showed the safe pattern; this sub-topic shows precisely what breaks without it, using the exact same shared students table so the before-and-after contrast is completely concrete.
What is... SQL injection? SQL injection is an attack where untrusted input (something a user typed) gets glued directly into a SQL command as text, letting that input change what the query actually does — not just what data it searches for. A single quote or a SQL keyword typed into what was supposed to be an ordinary name or search term can turn one intended query into a completely different one.

Here's the vulnerable version — building the SQL string directly with an f-string, using the same FakeCursor pattern from Sub-topic 3, but this time execute() is given the already-assembled string instead of a placeholder and separate params:

injection_vulnerable_demo.py
# FakeCursor stands in for a real mysql.connector cursor. This version's
# execute() takes the FULLY-BUILT sql string and, for demonstration only,
# checks whether it contains a classic injection payload -- a real MySQL
# server would actually run whatever SQL text it's handed, which is
# exactly the danger this demo is illustrating.

class FakeCursor:
    def __init__(self, table):
        self.table = table

    def execute_vulnerable(self, sql):
        print(f"SQL actually sent to the server: {sql}")
        if "OR '1'='1'" in sql:
            # A real server would match EVERY row here, since '1'='1' is
            # always true -- the attacker just bypassed the name filter
            # entirely and dumped the whole table.
            return list(self.table)
        name = sql.split("name = '")[1].rstrip("'")
        return [row for row in self.table if row["name"] == name]


students_table = [
    {"id": 1, "name": "Ana Torres", "grade": 91},
    {"id": 2, "name": "Ben Osei", "grade": 78},
]
cursor = FakeCursor(students_table)

# A normal, well-behaved search:
user_input = "Ana Torres"
sql = f"SELECT * FROM students WHERE name = '{user_input}'"
print(cursor.execute_vulnerable(sql))

print()

# An attacker's input instead of a real name:
malicious_input = "x' OR '1'='1"
sql = f"SELECT * FROM students WHERE name = '{malicious_input}'"
print(cursor.execute_vulnerable(sql))
actual output of injection_vulnerable_demo.py
SQL actually sent to the server: SELECT * FROM students WHERE name = 'Ana Torres'
[{'id': 1, 'name': 'Ana Torres', 'grade': 91}]

SQL actually sent to the server: SELECT * FROM students WHERE name = 'x' OR '1'='1'
[{'id': 1, 'name': 'Ana Torres', 'grade': 91}, {'id': 2, 'name': 'Ben Osei', 'grade': 78}]

The attacker never typed a real student's name at all — they typed x' OR '1'='1, and because that text was glued directly into the SQL string, the closing quote they included ended the intended string early and added a brand-new condition (OR '1'='1') that's always true, matching every row in the table instead of just one. The fix isn't "check the input for quotes" (attackers have countless other tricks) — it's to never build SQL out of untrusted text in the first place:

injection_fixed_demo.py
# FakeCursor here mimics execute(sql, params) exactly the way Sub-topic 3's
# safe version does -- the %s placeholder and separate params tuple, never
# string-building.

class FakeCursor:
    def __init__(self, table):
        self.table = table

    def execute(self, sql, params):
        name = params[0]  # treated strictly as DATA, never as SQL syntax
        return [row for row in self.table if row["name"] == name]


students_table = [
    {"id": 1, "name": "Ana Torres", "grade": 91},
    {"id": 2, "name": "Ben Osei", "grade": 78},
]
cursor = FakeCursor(students_table)

malicious_input = "x' OR '1'='1"
print(cursor.execute("SELECT * FROM students WHERE name = %s", (malicious_input,)))
actual output of injection_fixed_demo.py
[]

Same malicious input, completely different (and correct) result: an empty list, because no student is actually named x' OR '1'='1. The parameterized version never lets that text touch the SQL command's structure at all — it's compared against the name column as a plain string value, exactly like any other search term, which is precisely what makes injection impossible through this parameter.

Go Deeper: is this just a MySQL problem?

No — SQL injection affects any relational database reached with hand-built query strings (PostgreSQL, SQLite, SQL Server, and more), and it's been a top entry on industry-standard lists of critical web application security risks for over a decade, because the mistake is so easy to make by accident and so damaging when exploited (a real attacker armed with this technique has, in real incidents, read or deleted an entire production database). The fix is the same everywhere: never build a query string by concatenating untrusted input into it — always use that driver's parameterized-query mechanism instead.

Quick recap
  • SQL injection happens when untrusted input is glued directly into a query string, letting it change the query's actual behavior.
  • Parameterized queries close this gap by treating every substituted value strictly as data, never as SQL syntax.
  • Always use %s placeholders with a separate params tuple for any value coming from outside the program — no exceptions, no manual "sanitizing" instead.
Sub-topic 5 of 8

5. MongoDB and documents

At a glance
  • MongoDB is a document database: it stores records as flexible, JSON-like documents instead of fixed-column rows.
  • pymongo.MongoClient() connects; indexing the client by name gets a database, and indexing that by name gets a collection.
  • In Python, a MongoDB document IS a dict — no separate translation step needed the way SQL rows require one.
Why this matters: Sub-topics 2-4 covered MySQL's fixed-row-and-column world; MongoDB works on a genuinely different model, and understanding documents-as-dicts here directly is what makes Sub-topic 7's relational-vs-document comparison land.
What is... a document database? A document database stores each record as a self-contained, flexible structure (a "document") — similar to a JSON object — instead of forcing every record into the same fixed set of columns the way a relational table does. Different documents in the same collection can have different fields entirely, and a field can hold a nested structure (a list, or another document) directly, without needing a separate related table the way SQL would.

Here's what connecting to a real MongoDB server looks like — shown for reference, never executed in this course:

what_this_looks_like_for_real.py (reference only -- not run)
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
database = client["school_records"]
collection = database["students"]
What is... a collection? A collection is MongoDB's equivalent of a SQL table — a named group of related documents. Unlike a SQL table, though, a collection doesn't enforce that every document inside it has the same fields; it's a grouping, not a fixed structural contract.

Since a real server isn't available here, this chapter's runnable MongoDB examples use FakeCollection — a class storing documents in a plain Python list, exposing the same method names (insert_one, find, find_one, update_one, delete_one) a real pymongo collection would:

fake_mongo_setup.py
# FakeCollection stands in for a real pymongo Collection object, so this
# chapter's MongoDB examples run without a live server. Same method names
# as the real driver -- insert_one, find, find_one, update_one,
# delete_one -- operating on a plain Python list of dicts instead.

class FakeCollection:
    def __init__(self):
        self.documents = []

    def insert_one(self, document):
        self.documents.append(dict(document))
        return document

    def find(self, query=None):
        query = query or {}
        return [d for d in self.documents if all(d.get(k) == v for k, v in query.items())]

    def find_one(self, query=None):
        results = self.find(query)
        return results[0] if results else None


students = FakeCollection()
students.insert_one({
    "name": "Ana Torres",
    "grade": 91,
    "clubs": ["chess", "robotics"],   # a nested list -- no separate table needed
})
students.insert_one({
    "name": "Ben Osei",
    "grade": 78,
    # Ben has no "clubs" field at all -- perfectly valid, unlike a SQL table
    # where every row needs a value (or NULL) for every column.
})

for doc in students.find():
    print(doc)
actual output of fake_mongo_setup.py
{'name': 'Ana Torres', 'grade': 91, 'clubs': ['chess', 'robotics']}
{'name': 'Ben Osei', 'grade': 78}

Ana's document has a "clubs" field holding a whole nested list; Ben's document has no such field at all — both are completely valid documents in the same collection. This is the core difference from MySQL's rows: nothing here required declaring a fixed set of columns in advance, and a document's shape can vary from one record to the next.

Go Deeper: does MongoDB enforce any structure at all?

Real MongoDB deployments can optionally enforce a "schema" (a set of required fields and types per collection) using a feature called schema validation, but it's opt-in rather than the default — unlike a SQL table, which always enforces its column structure. Most introductory MongoDB use (and this chapter's examples) rely on the flexible, no-schema-required default, which is exactly what makes it a natural fit for data whose shape genuinely varies record to record.

Quick recap
  • MongoDB is a document database: records are flexible, JSON-like documents, not fixed rows.
  • MongoClient() connects; client[db_name][collection_name] reaches a specific collection.
  • A MongoDB document is a Python dict directly — different documents in the same collection can have different fields.
Sub-topic 6 of 8

6. CRUD with pymongo

At a glance
  • CRUD stands for Create, Read, Update, Delete — the four basic operations any data store needs.
  • insert_one(doc) creates; find_one(query)/find(query) reads; update_one(query, {"$set": ...}) updates; delete_one(query) deletes.
  • A query is itself a dict — {"name": "Ana Torres"} means "find documents where name equals "Ana Torres"."
Why this matters: these four methods are, in practice, almost everything a real application does with a MongoDB collection day to day — the same four verbs this course's own CSV-based projects (Chapter 13) and dict-based projects (Chapter 8) have already been doing, just against a real (or in this chapter's case, faked) database instead of an in-memory list.
What is... CRUD? CRUD is a standard acronym for the four fundamental operations any data-backed system supports: Create a new record, Read existing records, Update a record's fields, and Delete a record. Nearly every database driver — MySQL's, MongoDB's, and beyond — offers some version of these same four operations, just with different exact method names and syntax.
fake_mongo_crud.py
# FakeCollection again stands in for a real pymongo Collection, with the
# same method names and call shape the real driver uses.

class FakeCollection:
    def __init__(self):
        self.documents = []

    def insert_one(self, document):
        self.documents.append(dict(document))
        return document

    def find(self, query=None):
        query = query or {}
        return [d for d in self.documents if all(d.get(k) == v for k, v in query.items())]

    def find_one(self, query=None):
        results = self.find(query)
        return results[0] if results else None

    def update_one(self, query, update):
        doc = self.find_one(query)
        if doc is not None:
            doc.update(update.get("$set", {}))
            return True
        return False

    def delete_one(self, query):
        doc = self.find_one(query)
        if doc is not None:
            self.documents.remove(doc)
            return True
        return False


students = FakeCollection()

# Create
students.insert_one({"name": "Ana Torres", "grade": 91})
students.insert_one({"name": "Ben Osei", "grade": 78})

# Read
print("After insert:", students.find())
print("One student:", students.find_one({"name": "Ben Osei"}))

# Update
students.update_one({"name": "Ben Osei"}, {"$set": {"grade": 82}})
print("After update:", students.find_one({"name": "Ben Osei"}))

# Delete
students.delete_one({"name": "Ana Torres"})
print("After delete:", students.find())
actual output of fake_mongo_crud.py
After insert: [{'name': 'Ana Torres', 'grade': 91}, {'name': 'Ben Osei', 'grade': 78}]
One student: {'name': 'Ben Osei', 'grade': 78}
After update: {'name': 'Ben Osei', 'grade': 82}
After delete: [{'name': 'Ben Osei', 'grade': 82}]

Every step uses exactly the real pymongo method names and call shapes: insert_one(document) takes a plain dict; find(query)/find_one(query) take a dict describing what to match; update_one(query, {"$set": {...}}) takes a query dict plus an update dict wrapped in "$set" (MongoDB's real syntax for "change these fields, leave everything else alone"); delete_one(query) takes a query dict too.

What is... "$set"? {"$set": {"grade": 82}} is real MongoDB update syntax meaning "change the grade field to 82, leaving every other field on the document untouched." Without "$set", an update in real MongoDB would replace the entire document with whatever's passed — "$set" is specifically how a partial, field-by-field update is expressed.
Go Deeper: what about updating or deleting MANY documents at once?

update_one/delete_one only ever touch the first matching document; real pymongo also offers update_many and delete_many, which apply the same operation to every document matching the query instead of just the first one. This chapter sticks to the single-document versions since they cover the core pattern; reaching for the _many variants when genuinely needed is a small, natural extension once update_one/delete_one are second nature.

Quick recap
  • CRUD (Create, Read, Update, Delete) maps to insert_one, find/find_one, update_one, delete_one in pymongo.
  • A MongoDB query is a plain dict describing what to match, passed to find, update_one, or delete_one.
  • {"$set": {...}} updates specific fields while leaving the rest of a document unchanged.
Sub-topic 7 of 8

7. Relational rows vs. document-based records

At a glance
  • MySQL's rows have a fixed schema shared by every row in a table; related data lives in separate tables connected by a join.
  • MongoDB's documents have a flexible schema that can vary document to document; related data can be nested directly inside one document.
  • Neither is "better" universally — each fits a different shape of real-world data.
Why this matters: this is the conceptual payoff of covering both databases in one chapter — without this side-by-side comparison, MySQL and MongoDB would just look like two unrelated skills instead of two answers to the same underlying question: "how should this particular data be shaped?"

Picture the exact same student record, stored each way:

the same student, relational vs. document
RELATIONAL (MySQL) -- fixed columns, related data in separate tables
students table:              clubs table:
+----+------------+-------+  +----+------------+--------+
| id | name       | grade |  | id | student_id | club   |
+----+------------+-------+  +----+------------+--------+
| 1  | Ana Torres | 91    |  | 1  | 1          | chess  |
+----+------------+-------+  | 2  | 1          | robotics|
                              +----+------------+--------+
-- getting Ana's clubs requires a JOIN across both tables

DOCUMENT (MongoDB) -- one flexible, self-contained record
{
  "name": "Ana Torres",
  "grade": 91,
  "clubs": ["chess", "robotics"]   -- nested directly, no join needed
}
What is... a join? A join is how a relational database combines rows from two or more tables that are related by a shared value (like clubs.student_id matching students.id) into one combined result. Joins are one of SQL's most powerful features — but they only exist because relational data is deliberately split across separate, fixed-column tables in the first place, which is exactly the tradeoff a document database avoids by nesting related data directly inside one document instead.

The tradeoff runs both directions, and it's worth stating plainly:

Go Deeper: could the clubs example be modeled in MySQL without a separate table?

Technically, a text or JSON column could store something like "chess,robotics" or a JSON blob directly inside a MySQL row — but that gives up the ability to efficiently query "which students are in the chess club" without scanning and parsing every single row's text, which a separate clubs table with a proper join handles natively and efficiently. This is exactly the kind of tradeoff that "relational vs. document" is really about: not that one can't represent the other's data at all, but that each is naturally efficient at different kinds of queries over that data.

Quick recap
  • Relational databases use fixed-column rows and joins across separate tables for related data.
  • Document databases use flexible, self-contained documents that can nest related data directly.
  • Each fits a different shape of real-world data; production systems often use both, chosen per use case.
Sub-topic 8 of 8

8. Cloud-hosted connections & keeping credentials safe

At a glance
  • Connecting to a cloud-hosted database uses the exact same driver code — only the host (or connection string/URI) changes, from "localhost" to a remote address.
  • Credentials belong in environment variables (os.environ, Chapter 13's territory), never hardcoded in source code.
  • Real cloud connections use TLS (encryption in transit) so credentials and data aren't readable if intercepted over the network.
Why this matters: this is the sub-topic that makes everything else in this chapter production-ready rather than "toy code" — the exact same mysql.connector.connect() or MongoClient() calls from Sub-topics 2 and 5, pointed at a real, remote, possibly-shared database instead of a local one.

Nothing about the driver API changes when the database lives on a cloud provider's server instead of the same machine — only the value passed for the host (or, for MongoDB, the whole connection string) changes:

what_this_looks_like_for_real.py (reference only -- not run)
import os
import mysql.connector

# The SAME connect() call as Sub-topic 2 -- only host/user/password/database
# now come from environment variables instead of being hardcoded, and host
# points at a remote server instead of "localhost".
connection = mysql.connector.connect(
    host=os.environ["DB_HOST"],           # e.g. "my-database.cloudprovider.com"
    user=os.environ["DB_USER"],
    password=os.environ["DB_PASSWORD"],   # never hardcoded, never committed
    database=os.environ["DB_NAME"],
)

# MongoDB's equivalent: the whole address lives in one connection string/URI.
from pymongo import MongoClient
mongo_uri = os.environ["MONGO_URI"]  # e.g. "mongodb+srv://user:pass@cluster.mongodb.net/school_records"
client = MongoClient(mongo_uri)
What is... a connection string / URI? A connection string (or URI) packs a database's address, port, and sometimes credentials into a single string, rather than separate arguments — MongoDB's driver favors this style (mongodb+srv://user:password@host/database), while mysql-connector-python's connect() favors separate keyword arguments. Either style still comes from the same underlying source in production code: environment variables, not hardcoded text.

Chapter 13 introduced reading environment variables with os.environ for exactly this reason — a program's source code is often stored in a public or shared repository (like this course's own GitHub repo), but the actual password, API key, or full connection string a specific deployment uses should never live inside that source code at all. Instead, it's set as an environment variable on whatever machine actually runs the program, and the code just reads it at startup:

fake_cloud_connection_demo.py
# FakeConnection stands in for a real mysql.connector connection. This
# demo focuses on WHERE the credentials come from (os.environ, set here
# with os.environ[...] = ... only to simulate a deployment environment
# that already has them set -- a real program never sets its own
# credentials this way, it only reads ones set outside the program).

import os


class FakeConnection:
    def __init__(self, host, user, database):
        self.host = host
        self.user = user
        self.database = database

    def describe(self):
        return f"Connected to '{self.database}' on {self.host} as {self.user}"


# Simulating a deployment environment that already has these set --
# a real program would NOT set its own credentials like this; it would
# only read ones the hosting platform already configured.
os.environ["DB_HOST"] = "student-records.cloudprovider.example.com"
os.environ["DB_USER"] = "app_reader"
os.environ["DB_NAME"] = "school_records"

connection = FakeConnection(
    host=os.environ["DB_HOST"],
    user=os.environ["DB_USER"],
    database=os.environ["DB_NAME"],
)
print(connection.describe())
actual output of fake_cloud_connection_demo.py
Connected to 'school_records' on student-records.cloudprovider.example.com as app_reader

Not one credential appears as a literal string next to connect() or MongoClient() — every value is read through os.environ[...], which means the actual password (deliberately never even created in this safe demo) can differ per environment (a developer's laptop, a testing server, a production deployment) without ever changing a single line of source code, and can never accidentally end up committed to a public repository.

What is... TLS? TLS (Transport Layer Security) encrypts data in transit over a network connection — without it, credentials and data sent to a database could be read by anyone able to intercept the network traffic between a program and a remote server. Real cloud database services enable TLS by default (or require it) for exactly this reason; it's mentioned here as the reason a cloud connection string often includes +srv or an explicit ssl=true-style option, not something this chapter's offline examples need to configure themselves.
Go Deeper: what if a project needs MANY environment variables, not just one or two?

Real projects commonly use a local .env file (never committed — listed in .gitignore) alongside a library like python-dotenv to load many environment variables at once during local development, while a production deployment's hosting platform sets the real environment variables directly, with no file involved at all. The underlying pattern this chapter teaches — reading credentials through os.environ rather than hardcoding them — stays exactly the same either way; only how those variables get set in the first place changes.

Quick recap
  • The same driver code connects to a cloud-hosted database — only the host or connection string changes, from local to remote.
  • Credentials always come from environment variables at startup, never hardcoded in source code.
  • TLS encrypts real cloud connections in transit, protecting credentials and data from interception.
In the Real World

Points to Remember

← All Chapters Take the Quiz →