sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: items

ε祈祈猫儿з 提交于 2021-01-28 23:30:24

问题


I don't understand why I have this error. Please explain the error. I used official documentation.

I run Pipenv virtual env: python 3.8.2 sqlalchemy 1.3.16

You can try run this code too.

import enum

from sqlalchemy import create_engine, Column, Integer, String, Enum
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()


class Type(str, enum.Enum):
    ONE = "one"
    TWO = "two"


class Item(Base):
    __tablename__ = 'items'

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, unique=True, index=True)
    type = Column(Enum(Type), default=Type.ONE, nullable=False)


item = Item(name="item_name", type="one")
session.add(item)

print(Item.__table__)
session.commit()
for name in session.query(Item.name):
    print(name)

回答1:


I added:

engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
Base.metadata.create_all(bind=engine)
Session = sessionmaker(bind=engine)
session = Session()

It creates the tables in the database (there are ways of using SQLAlchemy with preexisting tables, so an explicit instruction isd necessary).



来源:https://stackoverflow.com/questions/61678766/sqlalchemy-exc-operationalerror-sqlite3-operationalerror-no-such-table-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!