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
- Sub-topic 1 is the entry point: what a database connection actually is, and why Python needs a driver library at all.
- Sub-topics 2-3 cover MySQL: connecting, cursors, parameterized queries, and fetching results with
mysql-connector-python. - Sub-topic 4 is the security payoff of Sub-topic 3: a concrete SQL injection attack, and the parameterized-query fix that closes it.
- Sub-topics 5-6 cover MongoDB: documents as Python dicts, and basic CRUD with
pymongo. - Sub-topic 7 is the conceptual payoff connecting both halves: relational rows vs. document-based records, side by side.
- Sub-topic 8 covers cloud-hosted connections — the exact same code, pointed at a remote host, with credentials from environment variables instead of hardcoded.
- This environment has no live database, and none is required. Every executed example uses a small
Fakeclass (FakeConnection,FakeCursor,FakeCollection) that mimics the real connector's interface — same method names, same call shape — without needing a real MySQL or MongoDB server. Real, uncommented connection snippets are shown too, clearly labeled as "what this looks like against a real server," but never executed. - Every method name and call signature taught here is the real one from
mysql-connector-pythonandpymongo— the mocking is only about what's safe to run in this course, not about teaching a simplified or invented API.
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.
1. What a database connection is, and why Python needs a driver
- 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-pythonfor MySQL,pymongofor 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.
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.
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.
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.
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.
- A database is separate software Python talks to over a network connection, not a file opened directly.
- A driver library (
mysql-connector-python,pymongo) translates Python calls into that database's protocol and back. - Both drivers follow the same shape: connect, get a working object, run a command, read results.
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.
- 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.
2. Connecting to MySQL with mysql-connector-python
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.
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:
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()
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:
# 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__)
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.
mysql.connector.connect(host=, user=, password=, database=)opens a real connection (shown for reference, not run here).connection.cursor()returns a cursor — the object every SQL command runs through.FakeConnection/FakeCursormimic that same shape so this chapter's examples run without a live server.
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.
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.
3. Cursors, execute(), and parameterized queries
cursor.execute(sql, params)runs a SQL command, with%splaceholders insqlfilled in safely from theparamstuple.cursor.fetchall()returns every matching row;cursor.fetchone()returns just the first one (orNone).connection.commit()saves changes made byINSERT/UPDATE/DELETEpermanently.
%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.
%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.
# 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())
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.
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.
cursor.execute(sql, params)uses%splaceholders filled in from a separateparamstuple — the safe way to include real values in a query.cursor.fetchall()returns every matching row as a list;cursor.fetchone()returns just the first, orNone.connection.commit()permanently saves changes made byINSERT/UPDATE/DELETEqueries.
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).
cursor.execute(sql, params)runs a query, with%splaceholders filled in safely from a separateparamstuple.fetchall()gets every matching row;fetchone()gets just the first, orNone.connection.commit()makes changes fromINSERT/UPDATE/DELETEpermanent.
4. SQL injection, and why parameterized queries matter
- 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 separateparamstuple) 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.
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:
# 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))
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:
# 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,)))
[]
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.
- Building SQL by gluing untrusted input directly into a string lets that input change the query's meaning, not just its data — this is SQL injection.
- Parameterized queries (
%s+ a separateparamstuple) are the fix, because substituted values are always treated strictly as data. - "Sanitizing" input by checking for quotes or keywords is not a reliable defense — using parameterized queries for every value, always, is.
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.
- 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
%splaceholders with a separate params tuple for any value coming from outside the program — no exceptions, no manual "sanitizing" instead.
5. MongoDB and documents
- 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.
Here's what connecting to a real MongoDB server looks like — shown for reference, never executed in this course:
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
database = client["school_records"]
collection = database["students"]
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:
# 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)
{'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.
- MongoDB stores records as flexible, JSON-like documents, not fixed-column rows.
MongoClient()connects; indexing by name reaches a database, then a collection.- A document in Python IS a dict — nested lists and dicts are stored directly, and different documents in the same collection can have different fields.
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.
- 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.
6. CRUD with pymongo
- 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 wherenameequals"Ana Torres"."
# 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())
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.
"$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.
- CRUD (Create, Read, Update, Delete) are the four fundamental operations, expressed in
pymongoasinsert_one,find/find_one,update_one, anddelete_one. - Queries are themselves plain dicts —
{"name": "Ana Torres"}matches documents where that field equals that value. {"$set": {...}}updates specific fields without replacing the whole document.
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.
- CRUD (Create, Read, Update, Delete) maps to
insert_one,find/find_one,update_one,delete_oneinpymongo. - A MongoDB query is a plain dict describing what to match, passed to
find,update_one, ordelete_one. {"$set": {...}}updates specific fields while leaving the rest of a document unchanged.
7. Relational rows vs. document-based records
- 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.
Picture the exact same student record, stored each way:
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
}
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:
- Relational (MySQL) fits data with a genuinely fixed, well-known shape and relationships that benefit from being queried flexibly across tables — financial ledgers, inventory systems, anything where consistency and structure matter more than flexibility.
- Document-based (MongoDB) fits data whose shape varies record to record, or where an entire related record naturally belongs nested inside its parent — a product catalog where different product categories have wildly different attributes, a content-management system's articles, user profiles with optional fields.
- Real production systems often use both, choosing per use case rather than picking one database for an entire company.
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.
- 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.
8. Cloud-hosted connections & keeping credentials safe
- 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.
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:
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)
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:
# 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())
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.
+srv or an explicit
ssl=true-style option, not something this chapter's
offline examples need to configure themselves.
- A cloud-hosted database uses the exact same driver code — only the host address (or connection string) points somewhere remote instead of local.
- Credentials belong in environment variables (
os.environ), read at startup, never hardcoded or committed to source control. - TLS encrypts a cloud connection in transit, protecting credentials and data from being read if intercepted over the network.
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.
- 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.
- Nearly every production web application, mobile app backend, and internal business tool is backed by a relational database (MySQL, PostgreSQL) or a document database (MongoDB) or both — this is one of the most universally applicable skills in this entire course.
- SQL injection remains one of the most consequential, most preventable security vulnerabilities in real software, precisely because the fix (parameterized queries, every time, no exceptions) is simple but easy to skip under deadline pressure.
- Reading credentials from environment variables instead of hardcoding them is standard practice at every company running real infrastructure — it's what makes the exact same code deployable across a developer's laptop, a staging server, and production without ever risking a leaked secret.
Points to Remember
- A database is separate software reached over a network connection; a driver library (
mysql-connector-python,pymongo) speaks its protocol on Python's behalf. - MySQL:
connect()opens a connection,.cursor()gets a cursor,cursor.execute(sql, params)runs a query with%splaceholders,fetchall()/fetchone()read results,connection.commit()saves changes. - SQL injection happens when untrusted input is glued directly into a query string; parameterized queries (
%s+ a separate params tuple) close this gap by treating substituted values strictly as data. - MongoDB:
MongoClient()connects,client[db][collection]reaches a collection, documents are plain Python dicts, and CRUD maps toinsert_one/find/update_one/delete_one. - Relational rows use a fixed schema and joins across tables; document-based records use a flexible schema and can nest related data directly — each fits a different shape of real-world data.
- A cloud-hosted connection uses the exact same driver code, pointed at a remote host via a connection string or URI, with credentials read from environment variables (never hardcoded) and TLS encrypting the connection in transit.
- Every example that actually ran in this chapter used a small Fake class mimicking the real driver's interface — the method names and call shapes taught are the genuine
mysql-connector-python/pymongoAPIs, just never pointed at a live server here.