- Here is a sample Python script that demonstrates how to perform CRUD (create, read, update, and delete) operations on a PostgreSQL database using the SQLAlchemy library, including how to perform complex joins:
- from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.orm import sessionmaker, relationship
- # Connect to the database
- engine = create_engine("postgresql://myuser:mypassword@localhost:5432/mydatabase")
- # Create the base class for declarative class definitions
- Base = declarative_base()
- # Define the ORM models for the tables
- class User(Base):
- __tablename__ = "users"
- id = Column(Integer, primary_key=True)
- username = Column(String)
- password = Column(String)
- class Order(Base):
- __tablename__ = "orders"
- id = Column(Integer, primary_key=True)
- user_id = Column(Integer, ForeignKey("users.id"))
- item = Column(String)
- user = relationship("User", back_populates="orders")
- # Create the tables in the database
- Base.metadata.create_all(engine)
- # Create a session to manage the database interactions
- Session = sessionmaker(bind=engine)
- session = Session()
- # CREATE
- # Insert a new user into the table
- user = User(username="john", password="password123")
- session.add(user)
- session.commit()
- # Insert a new order for the user
- order = Order(user=user, item="phone")
- session.add(order)
- session.commit()
- # READ
- # Select all users and their orders from the tables
- users = session.query(User).outerjoin(User.orders).all()
- # Print the users and their orders
- for user in users:
- print(f"Username: {user.username}")
- for order in user.orders:
- print(f" - Order: {order.item}")
- # UPDATE
- # Update the password for the user with the username "john"
- user = session.query(User).filter(User.username == "john").one()
- user.password = "newpassword456"
- session.commit()
- # DELETE
- # Delete the order with the item "phone"
- order = session.query(Order).filter(Order.item == "phone").one()
- session.delete(order)
- session.commit()
- # Close the session
- session.close()
- This script first connects to the PostgreSQL database using the SQLAlchemy create_engine function. It then defines the ORM (Object-Relational Mapping) models for the users and orders tables using the declarative_base and Column classes. The relationship function is used to define the relationship between the User and Order models.
- The script then creates the tables in the database using the create_all function. Next, it creates a session using the sessionmaker function, which allows you to manage the database interactions using the ORM models.
- # CREATE
- # Insert a new user into the table
- user = User(username="john", password="password123")
- session.add(user)
- session.commit()
- # Insert a new order for the user
- order = Order(user=user, item="phone")
- session.add(order)
- session.commit()
- # READ
- # Select all users and their orders from the tables
- users = session.query(User).outerjoin(User.orders).all()
- # Print the users and their orders
- for user in users:
- print(f"Username: {user.username}")
- for order in user.orders:
- print(f" - Order: {order.item}")
- # UPDATE
- # Update the password for the user with the username "john"
- user = session.query(User).filter(User.username == "john").one()
- user.password = "newpassword456"
- session.commit()
- # DELETE
- # Delete the order with the item "phone"
- order = session.query(Order).filter(Order.item == "phone").one()
- session.delete(order)
- session.commit()
- # Close the session
- session.close()
- This script demonstrates how to perform each of the CRUD operations using the ORM models and the session object:
- CREATE: Insert a new user and order into the users and orders tables by creating new User and Order objects and adding them to the session using the add method.
- READ: Select all users and their orders from the users and orders tables using the query method and the outerjoin function, and print the results.
- UPDATE: Update the password for the user with the username "john" by querying for the user using the query method and the filter function, updating the password attribute of the User object, and committing the changes to the database using the commit method.
- DELETE: Delete the order with the item "phone" by querying for the order using the query method and the filter function, deleting the Order object using the delete method, and committing the changes to the database using the commit method.
- Finally, the script closes the session using the close method.
- To perform complex joins in this script, you can use the join function in your query method. For example, to select all users and their corresponding orders from the users and orders tables, you could use a join function like this:
- users = session.query(User).join(User.orders).all()
- This will select all users and their orders from the users and orders tables where the id column in the users table matches the user_id column in the orders table. You can use other types of joins (e.g. outerjoin, fullouterjoin) and specify conditions in the filter function to further filter the results of the join.
- Watch: SQLAlchemy Turns Python Objects Into Database Entries
Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.
Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license