SQLAlchemy无法向表中添加数据

时间:2015-10-02 16:28:22

标签: python sqlalchemy

我使用以下代码创建了一个SQLite数据库,但是当我尝试将数据输入数据库时​​,没有任何内容出现。我不确定会出现什么问题..

创建数据库和表格的代码

# Create a database engine
engine = create_engine(r'sqlite:///Data\test.db', echo=True)
Base = declarative_base()

class Framework_Market(Base):  # Parent table for Child table

    __tablename__ = 'Market'  # Defining the Parent table name
    id = Column(Integer, primary_key=True)
    # Tables that it will create
    Country = Column(String(255))

    def __init__(self, market):
        self.market = market

class Framework_Equity(Base):

    __tablename__ = 'Equity'  # Defining Child Table
    id = Column(Integer, primary_key=True)
    # Tables that it will create
    Date = Column(Date)


    stock_id = Column(Integer, ForeignKey('Market.id'))
    stock = relationship("Framework_Market", backref=backref("Equity", order_by=id))

    def __init__(self, date):  

        self.date = date

# Create Tables
Base.metadata.create_all(engine)

向表格添加值的代码

engine = create_engine(r'sqlite:///Data\test.db', echo=True)

# Create a Session
Session = sessionmaker(bind=engine)
session = Session()

# Create a market
new_market = Framework_Equity("United States")
new_market.Equity = [Framework_Equity(datetime.date(2001, 1, 18))]  

# Add the record to session object - Putting it into the database
session.add(new_market)
session.commit()

截至目前,每当我运行代码将数据输入到表中,并尝试使用“DB Browser for SQLite”来查看它是否已记录到数据库中时,它会显示已创建一个空字段数据库。它不会在表中记录“美国”,也不会在连接表中记录“日期”。

我在这里做错了什么???

1 个答案:

答案 0 :(得分:1)

问题是您的列在Country = Column(String(255))中的名称为Framework_Market,但在__init__()方法中,您将值设置为self.market = market。与第二个模型相同:Date = Column(Date)self.date = date。将您的代码更改为以下内容,它将起作用:

class Framework_Market(Base):
    # ...

    def __init__(self, country):
        self.Country = country

class Framework_Equity(Base):
    # ...

    def __init__(self, date):  
        self.Date = date