python SQLALCHEMY我如何创建这个表?

oalqel3c  于 2023-02-28  发布在  Python
关注(0)|答案(1)|浏览(161)
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

4ktjp1zp

4ktjp1zp1#

为了便于结束,答案是将Meal类移到create_all语句之前,因为Meal语句是创建必要表的部分。

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()

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)

Base.metadata.create_all(bind=engine)

meal = Meal(id=1, sandwich='Libanais', fruit='banane', tablenumber=21)
print('----->', meal)

db.add(meal)
db.commit()

相关问题