首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多个写入线程上的Sqlalchemy

多个写入线程上的Sqlalchemy
EN

Stack Overflow用户
提问于 2017-12-07 10:55:28
回答 0查看 1.6K关注 0票数 0

以下代码在Python 3.6+中工作,而不是在Python3.4.3中,不确定它在哪个版本中失败。为什么会这样呢?我的印象是,sqlalchemy可能会通过将其隐藏在调用的序列化程序后面,来处理对基于文件的数据库的多个读取器/写入器。无论如何,这表明我没有正确处理这个问题--在低于3.6的版本中,如何在多个线程上插入,或者在主线程之外插入一个线程?

我在sqlalchemy session()级别的sqlalchemy connection pool on multiple threads上尝试过这样做。

但只能让它在引擎上工作,现在我只在3.6上找到了答案。

代码语言:javascript
复制
def insert_inventory_table(conn, table, inventory):
    conn.execute(table.insert(), inventory)    

def results_table(conn, table):
    q = select([table])
    data = conn.execute(q).fetchall()
    print('{!r}'.format(data))


def main_0():
    engine = create_engine('sqlite://', connect_args={'check_same_thread' : False})
    conn = engine.connect()

    metadata = MetaData(engine)
    table = Table('inventory',
              metadata,
              Column('item_no', Integer, primary_key=True, autoincrement=True),
              Column('desc', String(255), nullable=False),
              Column('volume', Integer, nullable=False)
              )

    metadata.create_all()

    some_inventory = [{'item_no' : 0, 'desc' : 'drone', 'volume' : 12},
                      {'item_no' : 1, 'desc' : 'puddle jumper', 'volume' : 2},
                      {'item_no' : 2, 'desc' : 'pet monkey', 'volume' : 1},
                      {'item_no' : 3, 'desc' : 'bowling ball', 'volume' : 4},
                      {'item_no' : 4, 'desc' : 'electric guitar', 'volume' : 3},
                      {'item_no' : 5, 'desc' : 'bookends', 'volume' : 2}]


    thread_0 = threading.Thread(target=insert_inventory_table, args=(conn, table, some_inventory[0:3]))
    thread_1 = threading.Thread(target=insert_inventory_table, args=(conn, table, some_inventory[3:]))

    thread_0.start()
    thread_1.start()

    return conn, table


if __name__ == '__main__':

    conn,table = main_0()
    results_table(conn, table)

谢谢。

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47686853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档