目录

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

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

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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()

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

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

原因在于少了建表语句:

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