Python provides various libraries and frameworks for working with databases, making it easy to interact with and manipulate data stored in databases. Two commonly used ways to work with databases in Python are through Object-Relational Mapping (ORM) frameworks like SQLAlchemy and using the Database Application Programming Interface (DB-API) for direct database access.
Object-Relational Mapping (ORM)
ORM is a programming technique that enables developers to work with relational databases in an object-oriented way. With ORM, developers can use object-oriented programming concepts like classes, objects, and inheritance to interact with the database, rather than using SQL directly. Python has many ORM frameworks, including SQLAlchemy, Django ORM, Peewee, Pony ORM, and more. In this example, we will use SQLAlchemy.
SQLAlchemy
SQLAlchemy is a popular and powerful ORM for Python that provides a high-level, SQL expression-based interface for interacting with databases. It supports multiple database engines, including SQLite, MySQL, PostgreSQL, and Oracle, and provides a simple and intuitive API that abstracts away the complexities of SQL and database interactions. Here is an example of how to use SQLAlchemy to interact with a SQLite database:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# create the engine to connect to the database
engine = create_engine('sqlite:///example.db', echo=True)
# create a base class to use for our declarative models
Base = declarative_base()
# define our model
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
# create the table
Base.metadata.create_all(engine)
# create a session to interact with the database
Session = sessionmaker(bind=engine)
session = Session()
# create a new user
new_user = User(name='Alice', email='alice@example.com')
session.add(new_user)
session.commit()
# retrieve all users from the database
users = session.query(User).all()
for user in users:
print(user.id, user.name, user.email)
In this example, we create an engine to connect to a SQLite database file called ’example.db’. We then define a User model using SQLAlchemy’s declarative syntax, which includes an id, name, and email column. We create the users table in the database using the Base class’s metadata.create_all method.
Next, we create a session object to interact with the database and add a new user to the database by creating a new instance of the User class, adding it to the session, and committing the transaction. Finally, we query the database for all users and print their id, name, and email.
Database Application Programming Interface (DB-API)
The DB-API is a Python specification for interacting with databases at a lower level than ORM frameworks. It defines a common interface for interacting with relational databases and allows Python programs to access a wide range of database systems through a consistent API. The DB-API specifies how Python programs can interact with databases and provides a set of common operations, such as connecting to a database, executing queries, and handling errors. Some commonly used DB-API implementations for Python include sqlite3, MySQL Connector, and psycopg2 for PostgreSQL.
Here is an example of using the sqlite3 module from the Python standard library to interact with a SQLite database:
import sqlite3
# connect to the database
conn = sqlite3.connect('example.db')
# create a cursor object
c = conn.cursor()
# create a new table
c.execute('''CREATE TABLE users
(id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
# insert a new user into the database
...