且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法通过Python使用高山Docker映像连接到Azure SQL

更新时间:2022-03-17 09:46:57

以确认设置:

apk update && apk add build-base unixodbc-dev freetds-dev
pip install pyodbc

为什么要同时安装unixodbc和freetds? Pyodbc的pip安装需要unixodbc-dev中的软件包以及build-base中的gcc库,因此无法解决。 freetds驱动程序与pyodbc的问题往往较少,而 pymssql 则在很大程度上依赖于我,我一直在docker中使用它来代替pyodbc。不过,这是个人喜好,您可以只包含unixodbc驱动程序。
现在,找到驱动程序

Why install both unixodbc and freetds? Pyodbc's pip install requires the packages in unixodbc-dev and the gcc libraries in build-base, so no getting around that. The freetds driver tends to have fewer issues with pyodbc, and is leaned on heavily by pymssql, which I've been using in docker in lieu of pyodbc. That's a personal preference, though, you could just include the unixodbc driver. Now, to find the driver

import pyodbc
pyodbc.drivers()
# []

Pyodbc找不到它们,但它们确实已安装,因此我们可以使用shell脚本找到它们:

Pyodbc can't locate them, but they are definitely installed, so we can find them with a shell script:

find / -name *odbc.so
/usr/lib/libtdsodbc.so
/usr/lib/libodbc.so

现在,我们可以使用子进程库将其自动化以手动设置驱动程序位置:

Now, we can automate this with the subprocess library to set the driver location manually:

import subprocess

s = subprocess.Popen('find / -name *odbc.so -type f', stdout=subprocess.PIPE, shell=True).communicate()

f, _ = s

# You can change this particular loop to select whatever driver you prefer
driver = [driver for driver in f.decode().split() if 'tds' in driver][0]

driver
# '/usr/lib/libtdsodbc.so'

username = 'someuser'
server = 'someserver'
database = 'somedatabase'

conn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)

或者,您可以将配置添加到 /etc/odbcinst.ini 中,如

Alternatively, you can add the configuration to /etc/odbcinst.ini as mentioned here:

[FreeTDS]
Description=FreeTDS Driver 
Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so

然后

import pyodbc

pyodbc.drivers()
['FreeTDS']