Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Building SQLAlchemy Objects | SQLAlchemy
Databases in Python

book
Building SQLAlchemy Objects

In this chapter, you'll learn how to set up your database session and add data to the database using SQLAlchemy. By the end, you'll understand how to create a session, add a new record, and save it. After creating the model, you can proceed to creating objects and saving them to the database.

1. Set Up the Session

A session is your primary tool for interacting with the database. Use sessionmaker to bind the engine and create a session:

python
Session = sessionmaker(bind=engine)
session = Session()

The Session() function creates an active session that serves as a workspace for staging and preparing database operations before they are committed.

2. Add a New Object

To add data, follow these steps:

  1. Create an Object
    Instantiate a model class (e.g., Product) with the required attributes.

    python
    new_product = Product(name="Laptop", description="High-end gaming laptop", price=1500)
  2. Stage the Object
    Add the object to the session with add().

    python
    session.add(new_product)
  3. Save the Changes
    Commit the session to finalize the transaction.

    python
    session.commit()
Taak

Swipe to start coding

  1. Initialize the database session using Session.
  2. Create a new object of the Product class with the specified attributes.
  3. Add the new object to the session using the appropriate method.
  4. Commit the transaction to save changes to the database.

Oplossing

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

# Initialize the database
engine = create_engine("sqlite:///data.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 a new product
new_product = Product(name="Laptop", description="High-end gaming laptop", price=1500)
session.add(new_product)
session.commit()

print(f"Added product: {new_product}")

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 4. Hoofdstuk 5
from sqlalchemy import create_engine, Column, Integer, String, Boolean
from sqlalchemy.orm import declarative_base, sessionmaker

# Initialize the database
engine = create_engine("sqlite:///data.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 = ___()

# Add a new product
new_product = ___(name="___", description="___", price=___)
session.___(new_product)
session.___()

print(f"Added product: {new_product.name}")

Vraag AI

expand
ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

We use cookies to make your experience better!
some-alt