找不到SQLAlchemy错误表

时间:2018-06-26 15:30:20

标签: python sqlalchemy

我是使用sqlAlchemy的新手,尝试插入数据条目时一直收到此错误。请告诉我我在做什么错。

test.py代码:

import sys
import sqlalchemy
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column,ForeignKey,Integer,String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine


engine = create_engine('sqlite:///restaurantmenu.db')
Base = declarative_base()


class Restaurant(Base):
   __tablename__ = "restaurant"
    name = Column(String(80),nullable=False)
    id = Column(Integer,primary_key=True)


class MenuItem(Base):
    __tablename__ = 'menu_item'
    name = Column(String(80),nullable=False)
    id = Column(Integer,primary_key = True)
    course = Column(String(250))
    description = Column(String(250))
    price = Column(String(9))
    restaurant_id = Column(Integer,ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)
Base.metadata.create_all(engine)

accessDatabase.py代码

import sys
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from test import Base,Restaurant,MenuItem

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine,autoflush=False)
session = DBSession()
MyFirstRestaurant = Restaurant(name = "Pizza Palace")
session.add(MyFirstRestaurant)
session.commit()
session.query(Restaurant).all()

当我运行accessDatabase.py并在session.commit行时出现问题

此处错误:

   sqlalchemy.exc.OperationalError: 
    (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block 
if this flush is occurring prematurely) 
(sqlite3.OperationalError) no such table: restaurant [SQL: 'INSERT INTO restaurant (name) VALUES (?)'] [parameters: ('Pizza Palace',)] 
(Background on this error at: http://sqlalche.me/e/e3q8)

2 个答案:

答案 0 :(得分:0)

请运行一次@media (max-width: 728px) { .st-accordion>ul>li:first-child .st-content {display:none!important;} } .st-accordion>ul>li:first-child .st-content {display:block;} 代码以创建包含所有表和元数据的数据库架构 然后继续运行test.py代码 这样做时,我得到以下结果

accessDatabase.py

Base.metadata.create_all(engine)不仅会创建架构,还会创建所有对象,关系,属性

答案 1 :(得分:0)

这都是一个愚蠢的错误。罪魁祸首是在创建表之前初始化引擎。将文件底部的这两行代码转移后。终于跑了。创建表后,应完成引擎和设置元数据。