SQLAlchemy ORM is a Python library that provides a high-level interface for interacting with relational databases using the Object-Relational Mapping (ORM) pattern
a How to Create a table using sqlachemy orm in python**
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///books.db')
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Student(Base):
__tablename__ = 'student'
id = Column(Integer, primary_key=True)
name = Column(String(50))
age = Column(Integer)
grade = Column(String(50))
Base.metadata.create_all(engine)
This code showcases the usage of SQLAlchemy ORM to define a database schema and interact with a SQLite database. Here's an explanation of each component:
1 Importing the necessary modules:
The code imports the required modules from SQLAlchemy to establish a connection to the database, define table columns, and create a session.
1 Creating the database engine:
create_engine('sqlite:///books.db') creates a connection to a SQLite database named "books.db". You can replace this URL with the appropriate one for your desired database system.
3 Creating a session:
Session = sessionmaker(bind=engine) creates a session class bound to the database engine.
session = Session() creates an actual session object that can be used to interact with the database.
4 Declaring the base class:
Base = declarative_base() creates a base class that serves as the parent for all declarative models.
5 Defining the Student model:
class Student(Base): defines a class named Student that inherits from the Base class.
tablename = 'student' specifies the name of the database table as "student".
id, name, age, and grade are attributes representing the columns of the student table. Each column has a data type associated with it.
6 Creating the table:
Base.metadata.create_all(engine) generates the table in the database based on the defined model. This step ensures the table structure matches the model.
b Inserting data into the table using SQLAlchemy
student1 = Student(name="Vincent", age=25, grade="Fifty")
student2 = Student(name="Ronald",age = 25, grade = "Fort
session.add(student1)
session.add(student2)
session.commit()
The provided code above is written in Python and utilizes an object-oriented approach to define two instances of a "Student" class that was defined previously. Here's an explanation of the code:
Two instances of the "Student" class are created:
The first instance is named "student1" and has the following attributes:
name: "Vincent"
age: 25
grade: "Fifty"
The second instance is named "student2" and has the following attributes:
name: "Ronald"
age: 25
grade: "Fort"
The next two lines, session.add(student1) and session.add(student2), suggest that there is a database session object named "session" which supports an "add" method. These lines indicate that the two student instances are being added to the session, implying that the session is used for interacting with a database.
Finally, session.commit() is used to commit the changes made to the session, presumably to save the added student records to the database,briefly you first create instance of the table ,add data to the session and commit session to the database.
b How to read data from Table.
Students = session.query(Student).order_by(Student.name)
for student in Students:
print(student.name)
Here's an explanation of the code:
The line Students = session.query(Student).order_by(Student.name) initiates a query on the "Student" table within the database. It retrieves all student records from the table and orders them based on the "name" attribute in ascending order.
The query result is assigned to the variable "Students". It is worth noting that this is just a variable name, and it could be named differently based on the author's preference.
The subsequent for loop iterates over each student object in the "Students" result set.
Within the loop, the line print(student.name) prints the name attribute of each student object to the console or standard output when you excute student.py file.
Inclusion SQLAlchemy ORM simplifies database operations in Python by abstracting away the complexities of SQL and allowing developers to work with database entities as Python objects and has Benefits such as improved code organization, increased productivity, and database portability.
Top comments (0)