SqlAlchemy 相当于使用 FreeTDS 的 pyodbc 连接字符串 [英] SqlAlchemy equivalent of pyodbc connect string using FreeTDS
问题描述
以下工作:
import pyodbc
pyodbc.connect('DRIVER={FreeTDS};Server=my.db.server;Database=mydb;UID=myuser;PWD=mypwd;TDS_Version=8.0;Port=1433;')
以下失败:
import sqlalchemy
sqlalchemy.create_engine("mssql://myuser:mypwd@my.db.server:1433/mydb?driver=FreeTDS& odbc_options='TDS_Version=8.0'").connect()
上面的错误信息是:
DBAPIError: (Error) ('08001', '[08001] [unixODBC][FreeTDS][SQL Server]无法连接到数据源 (0) (SQLDriverConnectW)') 无 无
DBAPIError: (Error) ('08001', '[08001] [unixODBC][FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnectW)') None None
有人能指出我正确的方向吗?有没有办法可以简单地告诉 sqlalchemy 将特定的连接字符串传递给 pyodbc?
Can someone please point me in the right direction? Is there a way I can simply tell sqlalchemy to pass a specific connect string through to pyodbc?
请注意:我想保持此无 DSN.
Please Note: I want to keep this DSN-less.
推荐答案
@Singletoned 的示例不适用于 SQLAlchemy 0.7.2.来自 用于连接到 SQL Server 的 SQLAlchemy 文档:
The example by @Singletoned would not work for me with SQLAlchemy 0.7.2. From the SQLAlchemy docs for connecting to SQL Server:
如果您需要上述选项之外的连接字符串,请使用 odbc_connect 关键字传入 urlencoded 连接字符串.传入的会进行urldecode直接传入.
为了使它工作,我使用了:
So to make it work I used:
import urllib
quoted = urllib.quote_plus('DRIVER={FreeTDS};Server=my.db.server;Database=mydb;UID=myuser;PWD=mypwd;TDS_Version=8.0;Port=1433;')
sqlalchemy.create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted))
这也适用于 Sybase.
This should apply to Sybase as well.
注意:在 python 3 中,urllib 模块已被拆分为多个部分并重命名.因此,python 2.7 中的这一行:
NOTE: In python 3 the urllib module has been split into parts and renamed. Thus, this line in python 2.7:
quoted = urllib.quote_plus
必须在python3中改为这一行:
has to be changed to this line in python3:
quoted = urllib.parse.quote_plus
这篇关于SqlAlchemy 相当于使用 FreeTDS 的 pyodbc 连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!