大家好,又见面了,我是你们的朋友全栈君。
依赖安装
pip install sqlacodegen
数据库配置config.py
import os
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import declarative_base, sessionmaker, Session
HOST = 'localhost'
PORT = 3306
USERNAME = 'root'
PASSWORD = 'root'
DB = 'demo'
DB_URI = f'mysql+pymysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DB}'
# 自动生成models
os.system(f'sqlacodegen {DB_URI} > models.py')
# 操作数据句柄
engine: Engine = create_engine(DB_URI)
Base = declarative_base(engine)
session: Session = sessionmaker(engine)()
右键运行config.py,会在当前目录生成models.py模型文件如下,该文件最好不要改动,后面数据库表改动的话,直接重新生成就好。
# coding: utf-8
from sqlalchemy import Column, DateTime, Integer, SmallInteger, String, TIMESTAMP, text
from sqlalchemy.dialects.mysql import TINYINT, VARCHAR
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class Admin(Base):
__tablename__ = 'admin'
id = Column(Integer, primary_key=True)
name = Column(String(50))
password = Column(String(50))
status = Column(Integer)
create_time = Column(DateTime)
update_time = Column(DateTime)
class AdminRole(Base):
__tablename__ = 'admin_role'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, nullable=False, comment='用户id')
role_id = Column(Integer, nullable=False, comment='角色id')
create_time = Column(TIMESTAMP, nullable=False, server_default=text("CURRENT_TIMESTAMP"), comment='创建时间')
操作数据库
from orm.config import session
from orm.models import Admin
session.add(Admin(name='张三丰', password='123456', status=1))
session.commit()
# 查询数据
admin__all = session.query(Admin.id).all()
print(admin__all)
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/150712.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...