Database access
Python Programming
by Gideon T. Marandu
Ardhi University
Introduction
• Interacting with databases is a common task in Python.
• Python comes with built-in support for SQLite Database.
• However, SQLite is not suitable for multi-user, multi-threaded access,
but it’s perfect for storing configuration or local data.
• SQLite simply stores all the data in a single file and allows us to access
that data using SQL syntax.
Using sqlite3 Connects to a local file named
mydb.db.
Runs some SQL query to put a
simple table in the database.
Then it queries
the same relation and prints one
of the results..
The Python Database API Specification v2.0 (DBAPI2)
• DBAPI2 Standard: SQLite's Python API follows the DBAPI2 specification, ensuring consistent
database interaction.
• Broad Applicability: Similar APIs exist for PostgreSQL, MySQL, Oracle, and other databases,
enabling uniform coding practices.
• DBAPI2 Specification: Database APIs following DBAPI2 include a connect function for
establishing connections.
• Connection Object: The connect function returns a Connection object, enabling database
interaction.
• Query Execution: Use the execute method on the Connection object to run queries.
• However, DBAPI2 is fairly low-level and difficult to work with.
Object-Relational Managers (ORMs)
• Object-Relational Managers (ORMs): Facilitate database interactions
using objects and map their attributes to relational databases.
• Popular Python ORM: SQLAlchemy is widely used and was the first
ORM ported to Python 3.
SQLAlchemy
• SQLAlchemy provides abstraction over database APIs, enabling code to
work across multiple database systems.
• SQLAlchemy and ORMs allow interaction with objects that automatically
modify and update database tables.
• Ease of Transition: Start with SQLite as a backend and later port to other
databases like MySQL with minimal changes.
• The latest stable version of SQLAlchemy is version 2.0
(https://www.sqlalchemy.org/ )
Using SQLAlchemy
• Database Connection: sqlalchemy.create_engine function
provides a single point of access for connecting to a database.
• The respective database connection function takes a huge number of
arguments to customize or tune access.
Create a class that allows objects to
Using SQLAlchemy store their data in the database. Each
table in the database is normally
represented by a separate class.
A special attribute named
__tablename__ to specify the name
of the table in the database
Connecting to a database
Ensures that all the tables associated with that
Base class exist. It also issue some sort of CREATE
TABLE call.
SQLAlchemy: Adding and querying objects
• Do it as an assignment
References
• Phillips, Dusty. Python 3 object oriented programming. Packt
Publishing Ltd, 2010.
• Lutz, Mark. Learning python: Powerful object-oriented programming.
" O'Reilly Media, Inc.", 2013.
QUESTIONS
?