Scrib 4
Scrib 4
Stepwise Implementation
Here, we are creating an object, and then with the use of the db.add() function, we have
added the created object to the database.
# New post created by a user, assumes # you get this from the frontendpost = Post(title="GFG
Article",
content="How to add SQL Alchemy objects",
published=True)
db.add(post)
As you can see above post is not saved to the database till you committed it like,
# To store the object to the database, # otherwise the transaction remains pendingdb.commit()
# After performing transaction, we should# always close our connection to the database# It's a
good practice and we must follow itdb.close()
print("Successfully added a new post")
Note: Every time you made changes make sure that you've committed the transaction,
otherwise the transaction is pending.
After committing the transaction you've successfully saved a new object to your database,
you can query the database regarding the changes
Under this, we are verifying if the object is successfully added or not. If it is added then the
database will show the same object else it won't be present in the database.
# This is the class which is mapped to "posts" # table to our databaseclass Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, nullable=False)
content = Column(String, nullable=False)
published = Column(Boolean, server_default='true', nullable=False)
Output:
Comment
More info
Campus Training Program
Next Article
Django ORM vs SQLAlchemy
Similar Reads
SQLAlchemy - Introduction
SQLAlchemy is basically referred to as the toolkit of Python SQL that provides developers
with the flexibility of using the SQL database. The benefit of using this particu...
15+ min read