将行添加到声明的表sqlalchemy

时间:2013-07-30 13:18:16

标签: python sqlalchemy

如何在数据库中向我的表中添加行,使用sqlalchemy? 我使用下一个代码:

   for i in range(count):
        name = Utils.uniqID()
        class name(Base):
            __tablename__ = name
            first = Column(Integer, primary_key = True)
            second = Column(String)
            third = Column(String)

            def __init__(self, first = None, second = None, third = None):
                self.first = first
                self.second = second
                self.third = third

        Base.metadata.create_all(engine)

我正在尝试使用下一个代码添加行:

def insertRandomRows(engine, table, count):
    rows = []
    for i in range(count):
        rows.append(table('af', 'adf', 'adf'))
    sessionmaker(bind = engine)().add_all(rows)
    enter code here

但他们没有出现在数据库中

1 个答案:

答案 0 :(得分:0)

解决方案:

def insertRandomRows(engine, table, count):
    rows = []
    for i in range(count):
        rows.append(table(randstr(), randstr(), randstr()))
    session = sessionmaker(bind = engine)()
    session.add_all(rows)
    session.commit()
    session.close()