前言
SQLAlchemy 可以结合 dataclass 使用,python3.7以上版本自带了dataclasses模块。
结合 dataclass 使用
使用示例
from dataclasses import dataclass, field
from datetime import datetime
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, TIMESTAMP
from sqlalchemy.orm import sessionmaker, mapper
metadata = MetaData()
person_table = \
Table('person', metadata,
Column('id', Integer, primary_key=True, autoincrement=True),
Column('name', String(255)),
Column('age', Integer),
Column('birthday', TIMESTAMP)
)
@dataclass
class Person:
id: int = None
name: str = field(default_factory=str)
age: int = field(default_factory=int)
birthday: datetime = field(default_factory=datetime)
mapper(Person, person_table)
engine = create_engine('mysql+pymysql://root:aa123456@47.108.155.10:3309/web', echo=True)
metadata.create_all(engine)
session = sessionmaker(bind=engine)()
# 新增数据提交
person = Person(name='Robby', age=33, birthday=datetime(1985, 7, 25))
session.add(person)
session.commit()
执行后,生成 person 表