Sobes.tech
Junior — Middle

Can you explain what SQLAlchemy is and how it is used in working with databases in Python?

sobes.tech AI

Answer from AI

SQLAlchemy is a popular ORM (Object-Relational Mapping) library for Python that simplifies working with databases. It allows you to describe tables and queries using Python classes and objects instead of writing raw SQL.

Main features:

  • Defining models (tables) as Python classes.
  • Creating, reading, updating, and deleting records through objects.
  • Automatically generating SQL queries.
  • Support for various DBMSs (PostgreSQL, MySQL, SQLite, etc.).

Example usage:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

new_user = User(name='Иван')
session.add(new_user)
session.commit()

user = session.query(User).filter_by(name='Иван').first()
print(user.name)  # Иван

SQLAlchemy simplifies working with databases, making the code more readable and portable.

Can you explain what SQLAlchemy is and how it is used… - sobes.tech