Python Programming Unit-5 (1)
Python Programming Unit-5 (1)
Database Programming:
Introduction:
1). Persistent Storage:
In any application, there is a need for persistent storage. Generally, there are three basic storage
mechanisms: files, a database system, or some sort of hybrid, such as an API that sits on top of
one of those existing systems, an ORM (Object-Relational Mapping), file manager,
spreadsheet, configuration file, etc.
Creating a Database
CREATE DATABASE test;
GRANT ALL ON test.* to user(s);
The first line creates a database named “test,” and assuming that you are a database
administrator, the second line can be used to grant permissions to specific users (or all of them)
so that they can perform the database operations that follow.
Using a Database
USE test;
If you logged into a database system without choosing which database you want to use, this
simple statement allows you to specify one with which to perform database operations.
Dropping a Database
DROP DATABASE test;
This simple statement removes all the tables and data from the database and deletes it from the
system.
Creating a Table
CREATE TABLE users (login VARCHAR(8), userid INT, projid INT);
This statement creates a new table with a string column login and a pair of integer fields, userid
and projid.
Dropping a Table
DROP TABLE users;
This simple statement drops a database table, along with all its data.
Inserting a Row
INSERT INTO users VALUES('leanna', 2111, 1);
You can insert a new row in a database by using the INSERT statement.You specify the table
and the values that go into each field. For our example, the string 'leanna' goes into the login
field, and 2111 and 1 to userid and projid, respectively.
Updating a Row
UPDATE users SET projid=4 WHERE projid=2;
UPDATE users SET projid=1 WHERE userid=311;
To change existing table rows, you use the UPDATE statement. Use SET for the columns that
are changing and provide any criteria for determining which rows should change. In the first
example, all users with a “project ID” (or projid) of 2 will be moved to project #4. In the second
example,
we take one user (with a UID of 311) and move him to project #1.
Deleting a Row
DELETE FROM users WHERE projid=%d;
DELETE FROM users;
To delete a table row, use the DELETE FROM command, specify the table from which you
want to delete rows, and any optional criteria. Without it, as in the second example, all rows
will be deleted.
paramstyle
The API supports a variety of ways to indicate how parameters should be integrated into an
SQL statement that is eventually sent to the server for execution. This argument is just a string
that specifies the form of string substitution you will use when building rows for a query or
command.
Function Attribute(s)
connect() Function access to the database is made available through Connection objects. A
compliant module must implement a connect() function, which creates and returns a
Connection object. Table 6-3 shows the arguments to connect().
You can pass in database connection information as a string with multiple parameters (DSN)
or individual parameters passed as positional arguments (if you know the exact order), or
more likely, keyword arguments. Here is an example of using connect() from PEP 249:
connect(dsn='myhost:MYDB',user='guido',password='234$')
The use of DSN versus individual parameters is based primarily on the system to which you
are connecting. For example, if you are using an API like Open Database Connectivity (ODBC)
or Java DataBase Connectivity (JDBC), you would likely be using a DSN, whereas if you are
working directly with a database, then you are more likely to issue separate login parameters.
Another reason for this is that most database adapters have not implemented support for DSN.
The following are some examples of non-DSN connect() calls. Note that not all adapters have
implemented the specification exactly, e.g., MySQLdb uses db instead of database.
Exceptions
Exceptions that should also be included in the compliant module as globals are shown in
Table 6-4.
ii). Connection Objects:
Connections are how your application communicates with the database. They represent the
fundamental mechanism by which commands are sent to the server and results returned. Once
a connection has been established (or a pool of connections), you create cursors to send requests
to and receive replies from the database.
Like commit(), rollback() only makes sense if transactions are supported in the database. After
execution, rollback() should leave the database in the same state as it was when the transaction
began. According to PEP 249, “Closing a connection without committing the changes first will
cause an implicit rollback to be performed.”
For example, should the Python string be converted to a VARCHAR, a TEXT, a BLOB, or a
raw BINARY object, or perhaps a DATE or TIME object if that is what the string is supposed
to be? Care must be taken to provide database input in the expected format; therefore, another
requirement of the DB-API is to create constructors that build special objects that can easily be
converted to the appropriate database objects. Table 6-7 describes classes that can be used for
this purpose. SQL NULL values are mapped to and from Python’s NULL object, None.
Commercial RDBMSs
• IBM Informix
• Sybase
• Oracle
• Microsoft SQL Server
• IBM DB2
• SAP
• Embarcadero Interbase
• Ingres
Open-Source RDBMSs
• MySQL
• PostgreSQL
• SQLite
• Gadfly
Database APIs
• JDBC
• ODBC
Non-Relational Databases
• MongoDB
• Redis
• Cassandra
• SimpleDB
• Tokyo Cabinet
• CouchDB
• Bigtable (via Google App Engine Datastore API)
If MySQL is not available in Python, you need to install the appropriate MySQL database
software and the Python MySQL connector. Follow these steps:
1. Install MySQL Server (If Not Installed)
If MySQL is not installed on your system, download and install it:
Windows: Download MySQL Installer from MySQL Official Website
3. Verify Installation
To check if MySQL is installed and accessible in Python, run:
import mysql.connector
print("MySQL Connector Installed Successfully!")
OR
import MySQLdb
print("MySQLdb Installed Successfully!")
4. Connect Python to MySQL
Now, test the connection:
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password"
)
if conn.is_connected():
print("Connected to MySQL successfully!")
conn.close()
# Commit changes
conn.commit()
print("\nUser Data:")
for row in rows:
print(row)
# Update data
cursor.execute("UPDATE users SET name = 'Alice Updated' WHERE name = 'Alice'")
conn.commit()
# Delete data
cursor.execute("DELETE FROM users WHERE name = 'Charlie'")
conn.commit()
Install psycopg2
First, install psycopg2 if it's not installed:
pip install psycopg2
How Python Interacts with PostgreSQL
• Connect to a PostgreSQL database.
• Create a cursor object to execute SQL queries.
• Execute queries such as SELECT, INSERT, UPDATE, and DELETE.
• Commit changes for INSERT or UPDATE operations.
• Fetch results for SELECT queries.
• Close the cursor and connection.
Example
This script demonstrates all methods and objects used to interact with PostgreSQL.
import psycopg2
print("\nUser Data:")
for row in rows:
print(row)
# Update data
cursor.execute("UPDATE users SET name = 'Alice Updated' WHERE name = 'Alice'")
conn.commit()
# Delete data
cursor.execute("DELETE FROM users WHERE name = 'Charlie'")
conn.commit()
Advantages:
• No installation required – Comes with Python by default
• Lightweight – Uses a single file to store data (.db file)
• Cross-platform – Works on Windows, Linux, and macOS
• Easy to use – No need for a dedicated database server
print("\nUser Data:")
for row in rows:
print(row)
# Update data
cursor.execute("UPDATE users SET name = 'Alice Updated' WHERE name = 'Alice'")
conn.commit()
# Delete data
cursor.execute("DELETE FROM users WHERE name = 'Charlie'")
conn.commit()
Install SQLAlchemy
pip install sqlalchemy
Example:
This example covers all CRUD (Create, Read, Update, Delete) operations using SQLAlchemy.
# Update a user
user.name = "Alice Updated"
session.commit()
# Delete a user
session.delete(user)
session.commit()
Non-Relational Databases:
Non-relational databases, also known as NoSQL databases, store data in key-value, document,
graph, or columnar formats instead of traditional tables and rows.
Example:
import redis
# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
# Set a key-value pair
r.set("username", "Alice")
# Store a list
r.rpush("fruits", "apple", "banana", "cherry")
Example:
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient("mongodb://localhost:27017/")
db = client["test_db"]
collection = db["users"]
# Insert a document
user = {"name": "Alice", "email": "[email protected]"}
collection.insert_one(user)
Example:
from cassandra.cluster import Cluster
# Connect to Cassandra
cluster = Cluster(['127.0.0.1'])
session = cluster.connect()
# Insert data
import uuid
session.execute("INSERT INTO users (id, name, email) VALUES (%s, %s, %s)",
(uuid.uuid4(), "Alice", "[email protected]"))
# Fetch data
rows = session.execute("SELECT * FROM users")
for row in rows:
print(row)
4. Neo4j (Graph Database)
Install Neo4j & Python Client
pip install neo4j
Example:
from neo4j import GraphDatabase
# Connect to Neo4j
uri = "bolt://localhost:7687"
driver = GraphDatabase.driver(uri, auth=("neo4j", "password"))
# Open Google
driver.get("https://www.google.com")
# Close browser
driver.quit()
import requests
import requests
# Data to send
data = {"title": "New Post", "body": "This is a test post", "userId": 1}
# Print response
print(response.json())
import requests
# Data to update
data = {"title": "Updated Title", "body": "Updated content", "userId": 1}
# Print response
print(response.json())
import requests
# Print response
print(response.json())
import requests
# API URL
url = "https://api.example.com/data"
# Print response
print(response.json())
Example: Handling Errors & Timeouts
A good web client should handle errors properly.
url = "https://www.example.com"
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Raise an error for bad responses (4xx, 5xx)
print(response.text)
except requests.exceptions.HTTPError as errh:
print("HTTP Error:", errh)
except requests.exceptions.ConnectionError as errc:
print("Connection Error:", errc)
except requests.exceptions.Timeout as errt:
print("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
print("Something went wrong:", err)
import requests
# Start a session
session = requests.Session()
# Login credentials
login_data = {"username": "testuser", "password": "securepass"}
# Perform login
session.post("https://example.com/login", data=login_data)
# Print response
print(response.text)
import requests
# Fetch data
response = oauth.get("https://api.example.com/protected-data")
print(response.json())
import requests
from requests.exceptions import HTTPError, Timeout
url = "https://example.com"
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Raise error for bad responses
print(response.json()) # Process response if successful
except HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except Timeout:
print("Request timed out")
except Exception as err:
print(f"Other error occurred: {err}")
import asyncio
import httpx
asyncio.run(main())
import requests
url = "https://example.com/large-file.zip"
print("Download complete!")
6. WebSockets for Real-Time Communication
Web clients can also handle real-time communication using WebSockets.
import asyncio
import websockets
asyncio.run(connect())
import cgi
How It Works:
It retrieves input from a form (name).
Prints the Content-Type header.
Generates an HTML response dynamically.
2. Restart Apache:
sudo systemctl restart apache2
Output:
Hello, John!
Advanced CGI:
Processing Form Data
CGI can handle multiple input fields.
import cgi
print("Content-Type: text/html\n")
form = cgi.FieldStorage()
name = form.getvalue("name")
email = form.getvalue("email")
print(f"<html><body>")
print(f"<h1>Thank You, {name}!</h1>")
print(f"<p>Your email: {email}</p>")
print(f"</body></html>")
import cgi
print("Content-Type: text/html\n")
print(f"<html><body>")
print(f"<h1>Your Message:</h1>")
print(f"<p>{message}</p>")
print(f"</body></html>")
import cgi
print("Content-Type: text/html\n")
try:
form = cgi.FieldStorage()
name = form.getvalue("name")
if not name:
raise ValueError("Name cannot be empty!")
print(f"<html><body><h1>Hello, {name}!</h1></body></html>")
except Exception as e:
print(f"<html><body><h1>Error:</h1><p>{e}</p></body></html>")
| <------------------------- | <------------------ |
Response Sent Request Processed Request Received
➢ If it's a static file (HTML, CSS, JS, images), it serves the file.
➢ If it's a dynamic request, it forwards it to a web application (e.g.,
Python CGI, Flask, Django).
• The server sends an HTTP response (e.g., an HTML page, JSON data, or an error).
• The client (browser) displays the response.
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, World! This is a Flask HTTP server."
if __name__ == "__main__":
app.run(debug=True)