👩💻 Develope/Python
[Python] SQLAlchemy
heywantodo
2023. 12. 13. 16:29
728x90
반응형
[Python] SQLAlchemy
SQLAlchemy란?
상업적으로 많이 사용되고있는 SQL 툴킷이며 Object Relational Mapper(ORM)이다.
클래스를 데이터베이스에 매핑할 수 있어서, 개체 모델과 데이터베이스 스키마를 완전히 분리된 방식으로 개발 할 수 있다.
🤔ORM (Object Relational Mapper)
객체와 관계형 데이터베이스의 데이터를 자동으로 매핑해주는 것을 말한다.
각 테이블 또는 구분하고자 하는 데이터 단위로 객체를 구현하고, 데이터 간의 관계를 형성한다.
객체 지향적인 코드로 인해 더 직관적이고 비지니스 로직에 더 집중할 수 있게 도와준다.
SQLAlchemy의 레이어 구조는 다음과 같다.
그렇다면 ORM을 사용하는 이유는 무엇일까?
- SQL 없이 OOP 언어로 DB 조작 가능
- 비지니스 로직에 집중할 수 있음
- 코드 재사용 및 유지 보수 용이
- DBMS에 민감하지 않음 ==> postgre/mysql와 같이 db 엔진이 다를 경우 syntax 에러가 발생 할 수 있는데, 그점에서 자유로움
- select a.name from a where city="seoul"
- select a.name from a where city='seoul'
SQLAlchemy 사용하기
https://docs.sqlalchemy.org/en/14/orm/quickstart.html#declare-models
ORM Quick Start — SQLAlchemy 1.4 Documentation
ORM Quick Start For new users who want to quickly see what basic ORM use looks like, here’s an abbreviated form of the mappings and examples used in the SQLAlchemy 1.4 / 2.0 Tutorial. The code here is fully runnable from a clean command line. As the desc
docs.sqlalchemy.org
나는 DB connection pool을 생성해두고, session을 가져와서 사용하는 방식으로 사용했다.
공식 문서에 나와있는 방법은 다음과 같다.
다음과 같이 DB engine (DB connection pool)을 생성한 후
from sqlalchemy import create_engine
engine = create_engine("sqlite://", echo=True, future=True)
session을 가져와서 사용한다.
from sqlalchemy import select
session = Session(engine)
stmt = select(User).where(User.name.in_(["spongebob","sandy"]))
for user in session.scalrs(stmt):
print(user)
728x90
반응형