from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Student(Base): __tablename__ = 'students' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) grade = Column(String(250), nullable=False) engine = create_engine('sqlite:///students.db') Base.metadata.create_all(engine)
from sqlalchemy.orm import sessionmaker from database_setup import Student, engine Session = sessionmaker(bind=engine) session = Session() new_student = Student(name='John Doe', grade='A') session.add(new_student) session.commit()
from sqlalchemy.orm import sessionmaker from database_setup import Student, engine Session = sessionmaker(bind=engine) session = Session() students = session.query(Student).all() for student in students: print(student.name, student.grade)In this example, we are querying all the students from our "students" table and printing their names and grades. We are using the sessionmaker function to create a session, and then querying the database using the query function provided by SQLAlchemy. Overall, Python database_setup Category is a useful tool for setting up and managing a database in a Python program. It is used with the SQLAlchemy library, which provides a powerful ORM for working with databases.