Working with SQLAlchemy
Create an engine
Create session
Create a table
Migrate
Getting Started
Open your code editor (vs code) save the file students.py navigate to the directory of students.py from the terminal on your vs code
HOW TO CREATE AN ENGINE
from the terminal, run these
- pip3 install sqlalchemy
- pip3 install psycopg2
from sqlalchemy import create_engine
engine = create_engine('postgresql://rukayat:rukayat@localhost:5432.., echo=False) ###to create an engine using postgresql
HOW TO CREATE A SESSION
from sqlalchemy.orm import session, sessionmaker
Session = sessionmaker(bind=engine) session = Session()
HOW TO CREATE A TABLE
from sqlalchemy import create_engine, Column, String, Integer 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))
#Migrate
Base.metadata.create_all(engine) ##This will create a table in the database
go to your terminal, run python3 students.py ###I saved my file as students.py
#To check if it has been created
- Go to your pg4admin -nagivate t0 Schema
- locate table
![Screenshot 2022-05-01 at 11.33.10.png] (cdn.hashnode.com/res/hashnode/image/upload/.. align="left")
HOW TO INSERT DATA INTO THE TABLE
Create instance of table class
Add data to session
Commit changes to database
student1 = Student(name='Will', age='24', grade='A')
session.add(student1)
session.commit()
### To add multiple inputs at the same time
student2 = Student(name='Shile', age='27', grade='B')
student3 = Student(name='Harry', age='25', grade='C')
session.add_all([student2, student3])
HOW TO READ DATA FROM THE TABLE
###Get data by Order
students = session.query(Student).order_by(Student.name)
for student in students:
print(student.name)
###Get data by filter
students = session.query(Student).filter(Student.name=='Will').first()
print(students.name, students.grade)
students = session.query(Student).filter(or_(Student.name=='Will', Student.name=='Shile'))
for student in students:
print(student.name)
#Count the number of results
student_count = session.query(Student).filter(or_(Student.name=='Will', Student.name=='Shile')).count()
print(student_count)
for more information, check out the docs click here
UPDATE DATA FROM THE TABLE
- Get the record
- Update the record
- Commit the change
student = session.query(Student).filter(Student.name=='Shile').first()
student.name = 'Kelvin'
session.commit()
DELETE DATA FROM THE TABLE
- Get the record
- Delete the record
- Commit the change
student = session.query(Student).filter(Student.name=='Kelvin').first()
session.delete(student)
session.commit()
After deletion, this is what my table looks like