fbpx

Database Interaction in Python: A Comprehensive Guide

Interacting with databases is a fundamental aspect of many applications, enabling the storage and retrieval of data. Python provides various libraries and modules to connect, query, and manipulate databases. In this guide, we’ll explore the basics of database interaction in Python, covering topics such as connecting to databases, executing queries, and using Object-Relational Mapping (ORM) libraries.

1. Connecting to Databases:

1.1 Using SQLite:

SQLite is a lightweight, serverless database engine that is commonly used for small to medium-sized applications.

import sqlite3

# Connect to a SQLite database (creates one if not present)
connection = sqlite3.connect('example.db')

# Create a cursor to execute SQL commands
cursor = connection.cursor()

# Execute SQL commands
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice', 30))

# Commit the changes and close the connection
connection.commit()
connection.close()

1.2 Using SQLAlchemy:

SQLAlchemy is a popular ORM that provides a high-level, Pythonic interface for interacting with databases.

from sqlalchemy import create_engine, Column, Integer, String, Sequence
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Define the data model
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = Column(String(50))
    age = Column(Integer)

# Connect to a database (SQLite in this example)
engine = create_engine('sqlite:///example.db')

# Create tables
Base.metadata.create_all(engine)

# Create a session to interact with the database
Session = sessionmaker(bind=engine)
session = Session()

# Add data to the database
user = User(name='Bob', age=25)
session.add(user)
session.commit()

# Query the database
users = session.query(User).all()
for u in users:
    print(f"User: {u.name}, Age: {u.age}")

2. Executing Queries:

2.1 Executing Queries with SQLite:

import sqlite3

# Connect to SQLite database
connection = sqlite3.connect('example.db')
cursor = connection.cursor()

# Execute SELECT query
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()

# Print results
for user in users:
    print(user)

# Close the connection
connection.close()

2.2 Executing Queries with SQLAlchemy:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Define the data model
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    age = Column(Integer)

# Connect to SQLite database
engine = create_engine('sqlite:///example.db')

# Create a session to interact with the database
Session = sessionmaker(bind=engine)
session = Session()

# Execute SELECT query
users = session.query(User).all()

# Print results
for user in users:
    print(f"User: {user.name}, Age: {user.age}")

3. ORM (Object-Relational Mapping):

3.1 Introduction to SQLAlchemy ORM:

SQLAlchemy ORM allows you to interact with databases using Python objects, providing a higher level of abstraction.

from sqlalchemy import create_engine, Column, Integer, String, Sequence
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Define the data model
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = Column(String(50))
    age = Column(Integer)

# Connect to SQLite database
engine = create_engine('sqlite:///example.db')

# Create tables
Base.metadata.create_all(engine)

# Create a session to interact with the database
Session = sessionmaker(bind=engine)
session = Session()

# Add data to the database
user = User(name='Charlie', age=28)
session.add(user)
session.commit()

# Query the database
users = session.query(User).all()
for u in users:
    print(f"User: {u.name}, Age: {u.age}")

4. Conclusion:

Interacting with databases in Python is a crucial skill for developers working on data-driven applications. Whether using a low-level approach with libraries like SQLite or adopting a high-level ORM like SQLAlchemy, understanding database interaction allows you to create applications that store and retrieve data efficiently. Consider the specific needs of your project, the scale of your data, and your preferences when choosing the appropriate database interaction approach in Python.