【问题标题】:Connect to sqlite3.Connection using sqlalchemy使用 sqlalchemy 连接到 sqlite3.Connection
【发布时间】:2020-05-25 15:39:07
【问题描述】:

我正在使用一个库,它通过调用sqlite3.connect(':memory:') 在内存中创建 SQLite 库。我想使用sqlalchemy 连接到这个数据库,以使用一些 ORM 和其他漂亮的花里胡哨。在 SQLAlchemy 的 API 的深处,是否有一种方法可以传递生成的 sqlite3.Connection 对象以便我可以重用它?

我不能只是重新连接connection = sqlalchemy.create_engine('sqlite:///:memory:').connect() - 正如SQLite documentation 所说:“数据库连接一关闭,数据库就不再存在。每个 :memory: 数据库都彼此不同。因此,打开两个数据库连接,每个连接的文件名为“:memory:”,将创建两个独立的内存数据库。” (说的有道理。我也试过了,行为符合预期。)

我试图按照 SQLAlchemy 的源代码找到建立数据库连接和实际调用 SQLite 的低级位置,但到目前为止我什么也没找到。看起来 SQLAlchemy 使用了太多晦涩难懂的炼金术来做到这一点,让我无法理解它发生的时间和地点。

【问题讨论】:

    标签: python sqlite sqlalchemy


    【解决方案1】:

    这是一种方法:

    # some connection is created - by you or someone else 
    conn = sqlite3.connect(':memory:')
    
    ... 
    
    def get_connection():
        # just a debug print to verify that it's indeed getting called:
        print("returning the connection") 
        return conn
    
    # create a SQL Alchamy engine that uses the same in-memory sqlite connection
    engine = create_engine('sqlite://', creator = get_connection)
    

    从现在开始,您可以随心所欲地使用引擎。

    这是此功能的a link to the documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      相关资源
      最近更新 更多