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

查看:64
本文介绍了在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天全站免登陆