在 SQLAlchemy 中,我可以从现有的 ODBC 连接创建引擎吗? [英] In SQLAlchemy, can I create an Engine from an existing ODBC connection?

查看:34
本文介绍了在 SQLAlchemy 中,我可以从现有的 ODBC 连接创建引擎吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个环境中工作,我获得了一个 ODBC 连接,该连接是使用我无权访问的凭据创建的(出于安全原因).但是,我想使用 SQLAlchemy 访问底层数据库 - 所以我的问题是,我可以将此 ODBC 连接传递给诸如 create_engine 之类的东西,或者以一种看起来像 SQLAlchemy 连接的方式包装它吗?

I am working in an environment where I am given an ODBC connection, which has been created using credentials to which I don't have access (for security reasons). However I would like to access the underlying database using SQLAlchemy - so my question is, can I pass this ODBC connection to something like create_engine, or alternatively, wrap it in such a way that it looks like a SQLAlchemy connection?

作为一个补充问题(并且在第一部分可以满足的乐观假设下工作)有没有一种方法可以告诉 SQLA 底层 RDBMS 使用什么方言?

As a supplementary question (and working on the optimistic assumption that the first part can be satisfied) is there a way that I can tell SQLA what dialect to use for the underlying RDBMS?

谢谢

推荐答案

是的,您可以:

from sqlalchemy import create_engine
from sqlalchemy.pool import StaticPool
eng = create_engine("mssql+pyodbc://", poolclass=StaticPool, creator=lambda: my_odbc_connection)

但是,如果您确实只创建了一个连接,而不是创建它们的可调用对象,则您必须仅在单个线程中使用此引擎,一次一个操作.在多线程应用程序中使用它不是线程安全的.

however, if you truly have only one connection already created, as opposed to a callable that creates them, you must only use this engine in a single thread, one operation at a time. It is not threadsafe for use in a multithreaded application.

如果 OTOH 你真的可以得到一个在调用时创建新连接的 Python 函数,这更合适:

If OTOH you can actually get at a Python function that creates new connections whenever called, this is much more appopriate:

from sqlalchemy import create_engine
eng = create_engine("mssql+pyodbc://", creator=my_odbc_connection_function)

上述引擎会正常连接池,可以自由地用作连接源.

the above engine will pool connections normally and can be used freely as a source of connectivity.

这篇关于在 SQLAlchemy 中,我可以从现有的 ODBC 连接创建引擎吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆