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()