Press "Enter" to skip to content

python数据库ORM建表提示表不存在

python数据库ORM建表提示表不存在

今天看orm教程时,用orm建表出现问题
原代码:

from re import T
from sqlalchemy import Column, create_engine,String,Integer, engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class math(Base):
    __tablename__ = 'math'
    id = Column(String(20), primary_key=True)
    name = Column(String(50))
    ms = Column(Integer)
engine = create_engine('mysql+mysqlconnector://root:password@localhost:3306/score')
DBsession = sessionmaker(bind=engine)
session = DBsession()
danco = math(id='001', name='danco', ms=99)
alex = math(id='002', name='alex', ms=93)
kudo = math(id='003', name='kudo', ms=92)
session.add(danco)
session.add(alex)
session.add(kudo)
session.commit()
session.close()

即建表并插入数据,此处报错:

sqlalchemy.exc.ProgrammingError: (mysql.connector.errors.ProgrammingError) 1146 (42S02): Table 'score.math' doesn't exist

原因在于少了建表语句:

Base.metadata.create_all(engine) #创建表结构

Be First to Comment

发表评论

您的电子邮箱地址不会被公开。