Working with Databases in Python#
In the previous chapter, we learned how relational databases organize data into tables, keys, and relationships, and why they are the core system of record in FinTech.
In this notebook, we will:
Connect from Python to a relational database (using SQLite).
Create the
customersandaccountstables from our examples.Insert sample data.
Run queries from Python that mimic real financial operations.
By the end, you will see how the theory of relational design turns into practical code that powers banking, trading, and payments systems.
Learning Objectives#
After working through this notebook, you should be able to:
Establish a database connection from Python using
sqlite3.Create tables with SQL from Python code.
Insert, update, and query data programmatically.
Use
pandasto analyze query results in a tabular, spreadsheet-like way.Understand how these skills extend to production databases (PostgreSQL, MySQL, etc.).
Setting Up the Database#
We’ll use the built-in sqlite3 module to create a lightweight in-memory database.
Although SQLite is not used for high-volume financial systems, its SQL behavior and connection
model make it an excellent teaching tool.
We’ll also define a helper function that returns query results as pandas DataFrames.
1import sqlite3
2import pandas as pd
3
4# For this notebook, we'll use an in-memory SQLite database.
5# In a real FinTech application, this would be a PostgreSQL/MySQL/Oracle instance.
6conn = sqlite3.connect(":memory:")
7
8# Helpful convenience so that query results come back as pandas DataFrames
9def run_query(sql, params=None):
10 if params is None:
11 params = ()
12 return pd.read_sql_query(sql, conn, params=params)
Creating Tables#
Before inserting any data, we define the schema for two tables:
customers — stores basic customer attributes
accounts — stores financial accounts that belong to customers
These definitions include primary keys and a foreign key to enforce relational structure.
1create_customers_sql = """
2CREATE TABLE customers (
3 customer_id INTEGER PRIMARY KEY,
4 first_name TEXT NOT NULL,
5 last_name TEXT NOT NULL,
6 state TEXT NOT NULL,
7 email TEXT NOT NULL UNIQUE
8);
9"""
10
11create_accounts_sql = """
12CREATE TABLE accounts (
13 account_id INTEGER PRIMARY KEY,
14 customer_id INTEGER NOT NULL,
15 type TEXT NOT NULL,
16 balance DECIMAL(12, 2) NOT NULL,
17 FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
18);
19"""
20
21with conn:
22 conn.execute(create_customers_sql)
23 conn.execute(create_accounts_sql)
24
25print("Tables created.")
Tables created.
CRUD Operations: The Core of Database Work#
Most applications — including banking, trading, and payments — interact with databases using the CRUD pattern:
Create: insert new records (insert)
Read: query existing records (select)
Update: modify stored data (update)
Delete: remove records (delete)
CREATE: Adding New Rows With INSERT#
The SQL INSERT statement adds a new row to a table.
General Syntax#
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
#### Why We Use Parameters (?)
Instead of writing values directly into SQL:
```sql
INSERT INTO customers VALUES (1, 'Test', 'User', 'NC', 'test@example.com')
we use parameterized queries:
INSERT INTO customers VALUES (?, ?, ?, ?, ?)
Parameters are important because:
They prevent SQL injection
They allow Python to handle data typing safely
They keep our code cleaner and easier to maintain
1with conn:
2 conn.execute(
3 "INSERT INTO customers (customer_id, first_name, last_name, state, email) VALUES (?, ?, ?, ?, ?)",
4 (1, "Test", "User", "NC", "test@example.com")
5 )
6
7run_query("SELECT * FROM customers")
| customer_id | first_name | last_name | state | ||
|---|---|---|---|---|---|
| 0 | 1 | Test | User | NC | test@example.com |
READ: Retrieving Data With SELECT#
The SQL SELECT statement retrieves rows from a table.
General Syntax#
SELECT column1, column2, ...
FROM table_name
WHERE conditions;
Key Concepts#
SELECT *returns all columns. However, it is preferable to select the specific columns you need.more maintainable in that it is clear what columns your code requires
protects your code from issues when the table schema changes
reduces the amount of data sent from the database to application
WHEREfilters rows
You can select only the columns you need
A SELECT query may return:
zero rows
one row = many rows
Unlike INSERT or UPDATE, SELECT returns a result set, which Python retrieves using a cursor.
Below, we show two ways to access the returned data:
By position (row[0], row[1], …)
By column name using SQLite’s
Reading Rows by Position#
When a query returns results, each row is a tuple:
row[0]→ first selected columnrow[1]→ second selected column
This is the most basic form of row access.
1cursor = conn.cursor()
2
3cursor.execute("""
4 SELECT first_name, last_name
5 FROM customers
6 WHERE state = 'NC'
7""")
8
9rows = cursor.fetchall()
10
11print("Results accessed by position:")
12for row in rows:
13 print("First Name:", row[0], "| Last Name:", row[1])
Results accessed by position:
First Name: Test | Last Name: User
Reading Rows by Column Name#
SQLite allows us to access row fields by column name when we configure:
conn.row_factory = sqlite3.Row
With this setting, each result row behaves like a dictionary:
- row["first_name"]
- row["last_name"]
This is much easier to read and maintain, especially in real applications.
1# Enable named column access
2conn.row_factory = sqlite3.Row
3cursor = conn.cursor()
4
5cursor.execute("""
6 SELECT first_name, last_name
7 FROM customers
8 WHERE state = 'NC'
9""")
10
11rows = cursor.fetchall()
12
13print("Results accessed by column name:")
14for row in rows:
15 print("First Name:", row["first_name"], "| Last Name:", row["last_name"])
Results accessed by column name:
First Name: Test | Last Name: User
UPDATE: Changing Existing Rows#
The SQL UPDATE statement modifies existing data in a table.
General Syntax#
UPDATE table_name
SET column1 = new_value
WHERE condition;
Always include a WHERE clause - otherwise all rows in the table will be updated.
Additionally, note that we use parameters as well here:
Inputs are safely escaped
Numeric/text types are handled correctly
User input cannot break or alter system logic
1with conn:
2 conn.execute(
3 "UPDATE customers SET email = ? WHERE customer_id = ?",
4 ("updated@example.com", 1)
5 )
6
7run_query("SELECT * FROM customers")
| customer_id | first_name | last_name | state | ||
|---|---|---|---|---|---|
| 0 | 1 | Test | User | NC | updated@example.com |
DELETE: Removing Records#
The SQL DELETE statement removes rows from a table.
General Syntax#
DELETE FROM table_name
WHERE condition;
Again, never delete without a WHERE clause or you will remove every row in the table.
1with conn:
2 conn.execute("DELETE FROM customers WHERE customer_id = ?", (1,))
3
4run_query("SELECT * FROM customers")
| customer_id | first_name | last_name | state |
|---|
Loading Multiple Records#
Now that we’ve mastered the CRUD basics, we can load multiple customers
and accounts records from the chapter. This dataset supports more realistic queries.
1customers = [
2 (5001, "Alice", "Jones", "NC", "alice.jones@email.com"),
3 (5002, "Bob", "Smith", "NY", "bob.smith@email.com"),
4 (5003, "Carol", "Lee", "CA", "carol.lee@email.com"),
5 (5004, "David", "Patel", "TX", "david.patel@email.com"),
6]
7
8accounts = [
9 (101, 5001, "Checking", 2500.00),
10 (102, 5002, "Savings", 5100.00),
11 (103, 5001, "Brokerage", 20000.00),
12]
13
14with conn:
15 conn.executemany(
16 "INSERT INTO customers (customer_id, first_name, last_name, state, email) VALUES (?, ?, ?, ?, ?)",
17 customers,
18 )
19 conn.executemany(
20 "INSERT INTO accounts (account_id, customer_id, type, balance) VALUES (?, ?, ?, ?)",
21 accounts,
22 )
23
24print("Sample data inserted.")
Sample data inserted.
1print("Customers:")
2display(run_query("SELECT * FROM customers"))
3
4print("Accounts:")
5display(run_query("SELECT * FROM accounts"))
Customers:
| customer_id | first_name | last_name | state | ||
|---|---|---|---|---|---|
| 0 | 5001 | Alice | Jones | NC | alice.jones@email.com |
| 1 | 5002 | Bob | Smith | NY | bob.smith@email.com |
| 2 | 5003 | Carol | Lee | CA | carol.lee@email.com |
| 3 | 5004 | David | Patel | TX | david.patel@email.com |
Accounts:
| account_id | customer_id | type | balance | |
|---|---|---|---|---|
| 0 | 101 | 5001 | Checking | 2500 |
| 1 | 102 | 5002 | Savings | 5100 |
| 2 | 103 | 5001 | Brokerage | 20000 |
Querying Data: FinTech-Style Questions#
Now that we have data, we can ask questions that resemble real use cases:
What accounts does a given customer own?
What is the total balance per customer across all their accounts?
Which customers have balances above a certain threshold?
1# 1. What accounts does Alice own?
2alice_accounts = run_query("""
3 SELECT c.first_name, c.last_name, a.account_id, a.type, a.balance
4 FROM customers c
5 JOIN accounts a ON c.customer_id = a.customer_id
6 WHERE c.first_name = 'Alice' AND c.last_name = 'Jones';
7""")
8display(alice_accounts)
9
10# 2. Total balance per customer
11balances_per_customer = run_query("""
12 SELECT c.customer_id,
13 c.first_name || ' ' || c.last_name AS customer_name,
14 SUM(a.balance) AS total_balance
15 FROM customers c
16 JOIN accounts a ON c.customer_id = a.customer_id
17 GROUP BY c.customer_id, customer_name
18 ORDER BY total_balance DESC;
19""")
20display(balances_per_customer)
| first_name | last_name | account_id | type | balance | |
|---|---|---|---|---|---|
| 0 | Alice | Jones | 101 | Checking | 2500 |
| 1 | Alice | Jones | 103 | Brokerage | 20000 |
| customer_id | customer_name | total_balance | |
|---|---|---|---|
| 0 | 5001 | Alice Jones | 22500 |
| 1 | 5002 | Bob Smith | 5100 |
From Raw SQL to Higher-Level Tools#
In this notebook, we used the built-in sqlite3 module and raw SQL strings to:
Open a database connection.
Create tables and insert data.
Run queries and pull results into pandas for analysis.
This pattern scales surprisingly far, but real FinTech systems often require:
Multiple database backends (PostgreSQL, MySQL, cloud-hosted services).
Connection pooling and efficient resource management.
Safer query construction to reduce risk of SQL injection.
A more Pythonic way to define tables and queries.
To handle those concerns, Python developers often use SQLAlchemy, a powerful library that provides:
A unified way to connect to many kinds of databases via a single “engine” interface.
Tools to build SQL queries programmatically.
An optional ORM (Object-Relational Mapper) layer for working with rows as Python objects.
In the next notebook, SQLAlchemy, we’ll refactor these ideas using SQLAlchemy’s engine and connection model, and see how it fits into realistic application code.