Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Reading from DB | SQLAlchemy
Databases in Python

book
Reading from DB

This chapter focuses solely on retrieving records from a database using SQLAlchemy. You’ll learn how to fetch single or multiple records efficiently using various querying methods.

Fetching a Single Record

To retrieve a single record, use query() and apply filters. For instance, to find a product by its name:

python
product = session.query(Product).filter(Product.name == "Laptop").first()

Here, .filter(Product.name == "Laptop") selects products with the name "Laptop," and .first() returns the first matching record or None.

Fetching Multiple Records

To retrieve multiple records, combine filter() with .all(). For example, to list all products:

python
products = session.query(Product).all()

To filter products, e.g., those priced above $1000, modify the query:

python
expensive_products = session.query(Product).filter(Product.price > 1000).all()

Using get() for Primary Key Lookups

For efficient retrieval by primary key, use get(). For example, fetching a product with ID 1:

python
product = session.query(Product).get(1)

Limiting Results

To limit the number of records retrieved, apply .limit(). For example, to fetch the first 3 products:

python
limited_products = session.query(Product).limit(3).all()

By mastering these techniques, you’ll efficiently retrieve the data you need, whether it’s a single record, multiple filtered results, or a limited subset.

Uppgift

Swipe to start coding

Complete the given code to retrieve all records from the products table in the database. Use the session object, the Product model, and the appropriate method to fetch all entries.

Lösning

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

# Initialize the database
engine = create_engine("sqlite:///example.db")
Base = declarative_base()

# Define the Product model
class Product(Base):
__tablename__ = "products"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
description = Column(String)
price = Column(Integer, nullable=False)
is_in_stock = Column(Boolean, default=True)

# Create tables
Base.metadata.create_all(engine)

# Set up the session
Session = sessionmaker(bind=engine)
session = Session()

# Add multiple products (one at a time)
products_to_add = [
{"name": "Laptop", "description": "High-end gaming laptop", "price": 1500},
{"name": "Smartphone", "description": "Latest model smartphone", "price": 800},
{"name": "Headphones", "description": "Noise-cancelling headphones", "price": 200}
]

# Iterate through the list and add each product one by one
for product in products_to_add:
new_product = Product(**product) # Unpack the dictionary as keyword arguments
session.add(new_product)
session.commit() # Commit after adding each product

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 6
from sqlalchemy import create_engine, Column, Integer, String, Boolean
from sqlalchemy.orm import declarative_base, sessionmaker

# Initialize the database
engine = create_engine("sqlite:///example.db")
Base = declarative_base()

# Define the Product model
class Product(Base):
__tablename__ = "products"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
description = Column(String)
price = Column(Integer, nullable=False)
is_in_stock = Column(Boolean, default=True)

# Create tables
Base.metadata.create_all(engine)

# Set up the session
Session = sessionmaker(bind=engine)
session = Session()

# Add multiple products (one at a time)
products_to_add = [
{"name": "Laptop", "description": "High-end gaming laptop", "price": 1500},
{"name": "Smartphone", "description": "Latest model smartphone", "price": 800},
{"name": "Headphones", "description": "Noise-cancelling headphones", "price": 200}
]

# Iterate through the list and add each product one by one
for product in products_to_add:
new_product = Product(**product) # Unpack the dictionary as keyword arguments
session.add(new_product)
session.commit() # Commit after adding each product

# Retrieve the products from the database
retrieved_products = ___.query(___).___()

print("\nAll products in the database:")
for product in retrieved_products:
print(product.name)

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt