0% found this document useful (0 votes)
9 views3 pages

Scrib 4

This article explains how to add objects to a database using SQLAlchemy ORM, specifically with a Postgres database. It provides a stepwise implementation including database configuration, adding a new post object, committing the transaction, and querying the database to verify the addition. The document includes code examples and best practices for managing database connections.

Uploaded by

Bhuvan Nagaraja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views3 pages

Scrib 4

This article explains how to add objects to a database using SQLAlchemy ORM, specifically with a Postgres database. It provides a stepwise implementation including database configuration, adding a new post object, committing the transaction, and querying the database to verify the addition. The document includes code examples and best practices for managing database connections.

Uploaded by

Bhuvan Nagaraja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

SQLAlchemy ORM - Adding Objects

Last Updated : 18 Mar, 2022





In this article, we will discuss how to add objects in the SQLAlchemy ORM.
The SQLAlchemy Object Relational Mapper presents a method of associating user-
defined Python classes with database tables and instances of those classes (objects) with
rows in their corresponding tables. For this article, we're going to use the Postgres
database. You can also use an in-memory-only SQL database.
Make sure you've properly installed sqlalchemy if not then install it with:

pip install sqlachemy


For example, You've designed an API that stores and fetches the posts created by the
user in the database, somewhat like GFG, Instagram, etc. This is the class that is mapped
to our database table "posts"
from sqlalchemy import Column, Integer, String, Booleanfrom sqlalchemy.ext.declarative
import declarative_base
# Declare MappingBase = declarative_base()
# 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)

Stepwise Implementation

Step 1: Database related configuration

from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker


# Syntax of database url = "<database_vendor_name>:# //<username>:<password>@ip-address/hostname/#
<database_name>"DB_URL = "postgresql://anurag:anurag@localhost/gfg"
engine = create_engine(DB_URL)
local_session = sessionmaker(autoflush=False,
autocommit=False, bind=engine)
# With this we get a session to do whatever# we want to dodb = local_session()

Step 2: To add a new object (post)

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

Step 3: Querying the database

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.

SELECT * FROM posts;


And you get all your posts saved in your local database.

Complete Script to add new objects to the database:


from sqlalchemy import Column, Integer, Boolean, Stringfrom sqlalchemy import
create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import
sessionmaker
# Declare MappingBase = declarative_base()

# 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)

# Syntax of database url = "<database_vendor_name>://#


<username>:<password>@ip-address/hostname/<database_name>"DB_URL =
"postgresql://anurag:anurag@localhost/gfg"
engine = create_engine(DB_URL)
local_session = sessionmaker(autoflush=False, autocommit=False, bind=engine)
# With this we get a session to do whatever we # want to dodb = local_session()
# 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)db.commit()
# After performing transaction, we should always close# our connection to the databasedb.close()
print("Successfully added a new post")

Output:

Comment
More info
Campus Training Program
Next Article
Django ORM vs SQLAlchemy
Similar Reads

Django ORM vs SQLAlchemy


For relational database newbies who are Python developers, Django ORM and SQLAlchemy
are two heavyweights worth considering. As Object-Relational Mappers (ORMs) they act a...
15+ min read

SQLAlchemy Cascading Deletes


SQLAlchemy is a powerful ORM (Object-Relational Mapping) library for Python that allows
developers to interact with relational databases using Python objects. It provides...
15+ min read

SQLAlchemy ORM - Creating Session


In this article, we will see how to create a session for SQLAlchemy ORM queries. Before we
begin, let us install the required dependencies using pip: pip install sqlalchem...
15+ min read

SQLAlchemy Core - Conjunctions


SQLAlchemy is a popular Python programming SQL toolkit and Object Relational Mapper
that gives application developers the full power and flexibility of SQL in a Pythonic w...
15+ min read

SQLAlchemy ORM - Declaring Mapping


In this article, we will see how to declare mapping using SQLAlchemy in Python. You will
need a database (MySQL, PostgreSQL, SQLite, etc) to work with. Since we are going...
15+ min read

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

Python Falcon - SQLAlchem

You might also like