在简单的python程序中直接使用sqlalchemy

database.py

from sqlalchemy import Integer, String, Column
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Users(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True)
    email = Column(String(64))

database.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session

from sql_app.models import Base


engine = create_engine(
    'mysql+mysqlconnector://root:123456@127.0.0.1:3306/dbname?charset=utf8mb4',
    echo=False,
    pool_size=8,
    pool_recycle=60 * 30
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base.metadata.create_all(bind=engine)


def get_db() -> Session:
    db = SessionLocal()
    return db

main.py

db = get_db()
res = db.query(models.Users).all()
print(res)
db.close()
posted @ 2023-11-01 16:41  bitterteaer  阅读(6)  评论(0编辑  收藏  举报