Distributed Databases and the Internet - Part II
Platform for Web-Based Database Applications
Connecting Web Applications to Databases
Recap: Web Database Fundamentals
Lecture Objectives & Roadmap
Database Connectivity - The Challenge
Solution Component: Database Drivers
Solution Component: Database APIs
How Drivers and APIs Work Together
Basic Database Interaction Flow
A typical sequence of operations using a driver/API:
import psycopg2
conn = psycopg2.connect(
dbname="mydatabase", user="myuser",
password="mypassword",
host="localhost",
port="5432")
Basic Database Interaction Flow
3. Create Statement: Obtain a Statement or PreparedStatement object from the Connection to execute SQL.
cur = conn.cursor()
4. Execute SQL Query: Send the SQL command (e.g., SELECT, INSERT, UPDATE, DELETE) using the Statement object.
sql_select = "SELECT product_name, price FROM products
WHERE category = 'Electronics’;"
cur.execute(sql_select, category_to_find)
Basic Database Interaction Flow
5. Process Results: If the query returns data (e.g., SELECT), iterate through the ResultSet object to retrieve rows and columns.
rows = cur.fetchall()
for row in rows:
print(row)
6. Close Connection: Release the database connection and associated resources (Crucial!).
cur.close()
Enhancing Efficiency - The Connection Cost Problem
The Solution: Connection Pooling
How Connection Pooling Works
1. It requests a connection from the pool.
2. If an idle, validated connection exists in the pool, it's "lent" to the application.
3. If no idle connection is available and the pool hasn't reached its maximum size, a new connection might be created and added.
4. If the pool is full, the application request may wait for a configured timeout or receive an error.
5. The application uses the borrowed connection to execute queries.
6. Crucially, when done, the application closes the logical connection handle, which signals the pool to return the underlying physical connection to the pool for reuse (it's not physically closed).
Benefits of Connection Pooling
Connection Pool Configuration & Analogy
Connection Pool Configuration & Analogy
Abstraction - The Object-Relational Challenge
The Solution: Object-Relational Mappers (ORMs)
Popular ORM Examples
ORMs exist for most major programming languages:
Popular ORM Examples
How ORMs Work: Functionality
How ORMs Work: Functionality
ORM Example (Python/SQLAlchemy-like)
ORM Example (Python/SQLAlchemy-like)
ORM Pros and Cons
ORM Pros and Cons
When to Use ORMs vs. Raw SQL
When to Use ORMs vs. Raw SQL
Drivers/APIs in Distributed Environments
Connection Pooling in Distributed Environments
ORMs in Distributed Environments
Security & Best Practices for Integration
Preventing SQL Injection: Parameterized Queries
Preventing SQL Injection: Parameterized Queries
Principle of Least Privilege
Connection String Security
Secure Error Handling
Lecture Summary: Connecting Applications to Databases