from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://root:1234@localhost:3306/lunch"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
db = SessionLocal()
Base.metadata.create_all(bind=engine)
class Meal(Base):
__tablename__ = 'meals'
id = Column(Integer, primary_key=True, autoincrement=True)
sandwich = Column(String(20), nullable=False)
fruit = Column(String(20), nullable=False)
tablenumber = Column(Integer)
def __repr__(self):
return '[{}, {}, {},{}]'.format(self.id, self.sandwich,
self.fruit, self.tablenumber)
meal = Meal(id=1, sandwich='Libanais', fruit='banane', tablenumber= 21)
print('----->', meal)
db.add(meal)
db.commit()
sqlalchemy.exc.ProgrammingError
:(pymysql.err.ProgrammingError
)(1146,“表'午餐.正餐'不存在”)[SQL:INSERT INTO meals (id, sandwich, fruit, tablenumber) VALUES (%(id)s, %(sandwich)s, %(fruit)s, %(tablenumber)s)] [parameters: {'id': 1, 'sandwich': 'Libanais', 'fruit': 'banane', 'tablenumber': 21}
](此错误的背景信息位于:http://sqlalche.me/e/13/f405)
1条答案
按热度按时间4ktjp1zp1#
为了便于结束,答案是将
Meal
类移到create_all
语句之前,因为Meal
语句是创建必要表的部分。即