原码:
#SQLAlchemy模型映射表结构.
from sqlalchemy import create_engine,Column,Integer,String
from sqlalchemy.ext.declarative import declarative_base# 数据库的变量
HOST = '127.0.0.1'
PORT = 3306
DATA_BASE = 'itbz'
USER = 'root'
PWD = '123456'
DB_URL = f'mysql+pymysql://{USER}:{PWD}@{HOST}:{PORT}/{DATA_BASE}'# 创建引擎
engine = create_engine(DB_URL)
# 创建一个基类
Base = declarative_base(engine)class Person(Base):__tablename__='t_person'id = Column(Integer,primary_key=True,autoincrement=True)name = Column(String(32))age = Column(Integer)country = Column(String(32))# 映射表结构
Base.metadata.create_all()
执行结果:
提示信息为:The ``declarative_base()`` function is now available as sqlalchemy.orm.declarative_base(). (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9)
表明sqlalchemy2.0以上时,sqlalchemy.ext.declarative已不适用
1. 更改引入的包
from sqlalchemy.orm import declarative_base
2.更改数据库引擎的引入方法
Base.metadata.create_all(engine)
修改后的原码
#SQLAlchemy模型映射表结构.
from sqlalchemy import create_engine,Column,Integer,String
from sqlalchemy.orm import declarative_base# 数据库的变量
HOST = '127.0.0.1'
PORT = 3306
DATA_BASE = 'itbz'
USER = 'root'
PWD = '123456'
DB_URL = f'mysql+pymysql://{USER}:{PWD}@{HOST}:{PORT}/{DATA_BASE}'# 创建引擎
engine = create_engine(DB_URL)
# 创建一个基类
Base = declarative_base()class Person(Base):__tablename__='t_person'id = Column(Integer,primary_key=True,autoincrement=True)name = Column(String(32))age = Column(Integer)country = Column(String(32))# 映射表结构
Base.metadata.create_all(engine)
执行结果: 执行成功,新表创建完成