from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Create a base class for our database
Base = declarative_base()
# Define a class for our teachers
class Teacher(Base):
__tablename__ = ‘teacher’
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
language_1 = Column(String)
language_2 = Column(String)
dob = Column(DateTime)
tax_id = Column(Integer)
phone_no = Column(String)
# Create a database connection using SQLAlchemy’s create_engine function
database_url = ‘sqlite:///teachers.db’
engine = create_engine(database_url)
# Create the tables in the database
Base.metadata.create_all(engine)
# Create a sessionmaker for our database
Session = sessionmaker(bind=engine)
# Create a session
session = Session()
# Add two new teachers to the database
session.add(Teacher(id=1, first_name=’John’, last_name=’Doe’, language_1=’ENG’, language_2=None, dob=’1990-01-01′, tax_id=11111, phone_no=’+491772345678′))
session.add(Teacher(id=2, first_name=’Jane’, last_name=’Smith’, language_1=’MAN’, language_2=’ENG’, dob=’1980-02-02′, tax_id=22222, phone_no=’+491443456432′))
# Commit the changes to the database
session.commit()
This code will create a SQLite database named ‘teachers.db’ with a table named ‘teacher’ containing the information of two teachers.
You can run this code in a Python script or in a Jupyter notebook. Make sure to install the necessary libraries by running pip install sqlalchemy
in your terminal or command prompt.
Please note that this is a very basic example and in a real-world scenario, you would need to handle exceptions, close sessions, and manage your database connections more carefully.
About Author
Discover more from SURFCLOUD TECHNOLOGY
Subscribe to get the latest posts sent to your email.