HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat N Strings
      • Python Example Code to Concat 2 Numbers
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
    • Modules and Libraries
      • Python Code to Load .SO File (and Invoke a Function)
      • Python Code for Automation using BDD
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Example Python Code to interact with databases using libraries like SQLAlchemy

What is SQLAlchemy?

SQLAlchemy is a powerful library for working with databases in Python. It provides tools for both SQL and Object-Relational Mapping (ORM). This means you can interact with databases using Python objects instead of writing raw SQL queries.

With SQLAlchemy, you can easily create, read, update, and delete data in your databases. It allows you to define database tables as Python classes and manage database connections. This abstraction makes it simpler to handle complex database operations.

SQLAlchemy is popular for its flexibility and ease of use. It supports various databases like SQLite, MySQL, and PostgreSQL. Whether you’re building a small application or a large-scale project, SQLAlchemy helps streamline your database interactions.

Setting Up SQLAlchemy

Before using SQLAlchemy, you need to install it. Use pip to install SQLAlchemy:

pip install SQLAlchemy

SQLAlchemy requires a database driver. For example, use sqlite for SQLite databases. Install the necessary driver using pip as well.

Creating a Database Connection

To interact with a database, first create a connection. Here’s how you can connect to an SQLite database:

from sqlalchemy import create_engine

# Create a database engine
engine = create_engine('sqlite:///example.db')

The create_engine function creates a connection to the database. The URL format for SQLite is sqlite:///database_name.db. This example connects to a database file named example.db.

Defining Database Models

Define models to represent database tables. Use SQLAlchemy’s ORM to map classes to tables:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()

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

In this example, the User class represents a table called users. Each class attribute corresponds to a column in the table.

Creating the Database Tables

Once models are defined, create the tables in the database:

# Create tables in the database
Base.metadata.create_all(engine)

The create_all method creates the tables based on the defined models. This step initializes the database with the appropriate schema.

Adding and Querying Data

Insert data into the database and query it using SQLAlchemy:

from sqlalchemy.orm import sessionmaker

# Create a session
Session = sessionmaker(bind=engine)
session = Session()

# Add a new user
new_user = User(name='Alice', age=30)
session.add(new_user)
session.commit()

# Query the database
users = session.query(User).all()
for user in users:
    print(user.name, user.age)

Create a session to interact with the database. Add a new User instance and commit it to save changes. Query all users and print their details.

Updating and Deleting Data

Update and delete records with SQLAlchemy:

# Update a user
user = session.query(User).filter_by(name='Alice').first()
user.age = 31
session.commit()

# Delete a user
session.delete(user)
session.commit()

Find a user and update their information. Commit changes to the database. To delete a record, find it and use the delete method, then commit the changes.

Detailed Example using SQLAlchemy with Python

Let’s see yet another detailed example that demonstrates how to use SQLAlchemy to interact with a database. This example includes creating a database, defining models, adding, querying, updating, and deleting data, and displays the results.

Example Code

# Import necessary modules
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Create a new SQLite database (or connect to an existing one)
engine = create_engine('sqlite:///example.db', echo=True)

# Define the base class for declarative models
Base = declarative_base()

# Define a User model
class User(Base):
__tablename__ = 'users'

id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)

# Create tables in the database
Base.metadata.create_all(engine)

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

# Add new users to the database
new_user1 = User(name='Alice', age=30)
new_user2 = User(name='Bob', age=25)
session.add(new_user1)
session.add(new_user2)
session.commit()

# Query all users from the database
users = session.query(User).all()
print("Users after adding:")
for user in users:
print(f"ID: {user.id}, Name: {user.name}, Age: {user.age}")

# Update a user's age
user_to_update = session.query(User).filter_by(name='Alice').first()
if user_to_update:
user_to_update.age = 31
session.commit()

# Query all users again to see the update
users = session.query(User).all()
print("\nUsers after updating Alice's age:")
for user in users:
print(f"ID: {user.id}, Name: {user.name}, Age: {user.age}")

# Delete a user from the database
user_to_delete = session.query(User).filter_by(name='Bob').first()
if user_to_delete:
session.delete(user_to_delete)
session.commit()

# Query all users again to see the deletion
users = session.query(User).all()
print("\nUsers after deleting Bob:")
for user in users:
print(f"ID: {user.id}, Name: {user.name}, Age: {user.age}")

# Close the session
session.close()

Explanation

1. Setup

– Creates an SQLite database named `example.db`.
– Defines a `User` model with `id`, `name`, and `age` columns.
– Creates tables based on the defined model.

2. Add Data

– Adds two new users, Alice and Bob, to the database.

3. Query Data

– Queries and prints all users in the database.

4. Update Data

– Updates Alice’s age from 30 to 31 and commits the change.
– Queries and prints all users to show the update.

5. Delete Data

– Deletes Bob from the database.
– Queries and prints all users to show the deletion.

6. Close Session

– Closes the database session.

Output

When running the code, you should see output similar to this:

Users after adding:
ID: 1, Name: Alice, Age: 30
ID: 2, Name: Bob, Age: 25

Users after updating Alice's age:
ID: 1, Name: Alice, Age: 31
ID: 2, Name: Bob, Age: 25

Users after deleting Bob:
ID: 1, Name: Alice, Age: 31

This output demonstrates adding, updating, and deleting records using SQLAlchemy. The `echo=True` parameter in `create_engine` will also show the SQL statements being executed, which helps in understanding the underlying operations.

SQLAlchemy simplifies database interactions in Python. It provides tools for defining models, creating tables, and performing CRUD operations. With SQLAlchemy, you can efficiently manage database operations using Python code.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas
  • Example Python Code to Plot Data Using Matplotlib

No luck finding what you need? Contact Us

Previously
Python Code to Handle User Authentication in Flask
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.