SQLAlchemy is a powerful Python library that simplifies working with databases, enabling developers to interact with databases using Python code rather than writing raw SQL queries. In this Answer, we’ll dive into using CRUD operations in SQLAlchemy, covering the essential techniques and patterns to create, retrieve, update, and delete data from the database.
Let's discuss how to perform CRUD operations in SQLAlchemy:
We establish a database connection with the create_engine("sqlite:///:memory:")
command, which initializes an SQLite database in memory.
Note: For a more detailed explanation of how to connect with databases in SQLAlchemy, you can read this Answer.
Following that, we define our database table using the declarative_base()
class. Here, we define a database table named “Educative_Answers
”, consisting of columns for id
and name
.
Note: For a more detailed explanation of how to create a table in SQLAlchemy, you can read this Educative Answer.
from sqlalchemy import create_engine, Column, Integer, Stringfrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmaker# Create an in-memory SQLite database engineengine = create_engine('sqlite:///:memory:')# Define Table ClassesBase = declarative_base()class CustomTable1(Base):__tablename__ = 'Educative_Answers'custom_id = Column(Integer, primary_key=True)custom_name = Column(String, unique=True)# Create the tables in the in-memory databaseBase.metadata.create_all(engine)# Establish a session for CRUD operationsSession = sessionmaker(bind=engine)session = Session()
To add new records, create a session and add instances of your model with the new entry. We used session.add()
method to create new records and session.commit()
to confirm changes in SQLAlchemy.
# Function to Create Recordsdef create_record(session, name):new_record = CustomTable1(custom_name=name)session.add(new_record)session.commit()return new_record# Example of using the create_record functioncreate_record(session, 'SQLAlchemy Crud Operations')create_record(session, 'SQLAlchemy Sessions')# Query and print all entries from the databaseall_records = session.query(CustomTable1).all()print("All Entries in the Table:")for record in all_records:print(f"ID: {record.custom_id}, Name: {record.custom_name}")
Lines 1–6: These lines define a function, create_record()
, which is intended for adding new records to the table. The session.add()
function is employed to insert a new record, while the session.commit()
function ensures its persistence in the database.
Lines 8–9: These lines simply utilize the specified function to insert new records into the database.
Line 13–16: These lines retrieve and print all data from the database on the console.
We can use session.query()
method to read records from the database in SQLAlchemy. Furthermore, we can use multiple sub-methods to filter our records.
Note: You can read this Educative Answer for more detailed work on how to execute queries in SQLAlchemy.
# Query and print all entries from the databaseall_records = session.query(CustomTable1).all()print("All Entries in the Table:")for record in all_records:print(f"ID: {record.custom_id}, Name: {record.custom_name}")
Modify records within a session and commit to confirm the changes. Utilize conditional statements to verify the existence of specific entries in the database before applying modifications.
# Function to Update Recordsdef update_record(session, record_id, new_name):record_to_update = session.query(CustomTable1).get(record_id)if record_to_update:record_to_update.custom_name = new_namesession.commit()return record_to_updateelse:return None# Example of using the update_record functionupdated_record = update_record(session, 1, 'Not SQLALchemy')if updated_record:print(f"Updated Record - ID: {updated_record.custom_id}, New Name: {updated_record.custom_name}")else:print("Record with specified ID not found.")# Query and print all entries from the database after updateall_records_after_update = session.query(CustomTable1).all()print("All Entries in the Table After Update:")for record in all_records_after_update:print(f"ID: {record.custom_id}, Name: {record.custom_name}")
Lines 1–9: These lines define the update_record()
function, which queries the record designated for updating and subsequently modifies its value. The session.commit()
function ensures the changes are persistently stored in the database.
Lines 12–16: These lines utilize the specified function to update existing records in the database and print the updates on the console. If the specific record is not found in the database, it also logs that information.
Line 19–22: These lines retrieve and print all data from the database on the console.
To delete records, create a session and used session.delete()
method with the record ID as a parameter to delete that particular record and session.commit()
to confirm changes in SQLAlchemy.
# Function to Delete a Recorddef delete_record(session, record_id):record_to_delete = session.query(CustomTable1).get(record_id)if record_to_delete:session.delete(record_to_delete)session.commit()return Trueelse:return False# Query and print all entries from the database before deletionall_records_after_deletion = session.query(CustomTable1).all()print("All Entries in the Table Before Deletion:")for record in all_records_after_deletion:print(f"ID: {record.custom_id}, Name: {record.custom_name}")# Example of using the delete_record functionrecord_id_to_delete = 1 # Replace with the actual ID of the record to deleteis_deleted = delete_record(session, record_id_to_delete)# Query and print all entries from the database after deletionall_records_after_deletion = session.query(CustomTable1).all()print("All Entries in the Table After Deletion:")for record in all_records_after_deletion:print(f"ID: {record.custom_id}, Name: {record.custom_name}")
Lines 1–9: These lines define a function, delete_record()
, designed to remove existing records from the table. The session.delete()
function is utilized for deleting a specific record, and the session.commit()
function ensures its persistence in the database.
Lines 12–25: These lines essentially display all the records from the database both before and after deleting a specific record, demonstrating the successful deletion process.
By mastering SQLAlchemy’s CRUD operations, we can seamlessly interact with databases, making our Python applications more dynamic and data-driven. This guide serves as a starting point for leveraging the full capabilities of SQLAlchemy in our projects. Happy coding!
Free Resources