「SQLAlchemy」を試してみる

usage

下記のような感じ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from sqlalchemy import Column, ForeignKey, Integer, String, Text, TIMESTAMP
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

Base = declarative_base()


engine = create_engine('postgresql://user_name:password@localhost:5432/db_name')
Session = sessionmaker(bind=engine)

class Users(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
status = Column(Integer)
profile = Column(Text)
created_at = Column(TIMESTAMP)


Base.metadata.create_all(engine)

session = Session()

# 全件取得
result = session.query(Users).all() # .all() は省略可
for user in result:
print(user.id, user.status, user.profile, user.created_at)