我有一个基于alpine的docker镜像,支持Python,我试图通过它连接到Azure SQL服务。这是我简单的连接代码。连接到Azure中的SQL Server时出现错误。
conn = pyodbc.connect('DRIVER ='+ driver +'; SERVER ='+ server +'; PORT = 1433; DATABASE ='+ database +'; UID ='+ username +'; PWD ='+ password)pyodbc.Error :( '01000',“[01000] [unixODBC] [驱动程序管理器]无法打开lib'用于SQL Server的ODBC驱动程序17':找不到文件(0)(SQLDriverConnect)”)nect)“)
import pyodbc
server = 'blah1.database.windows.net'
database = 'mydb1'
username = 'myadmin'
password = 'XXXXXX'
driver= 'ODBC Driver 17 for SQL Server'
conn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
c = conn.cursor()
c.execute("SELECT * FROM dbo.customers")
print(c.fetchall())
print(type(c.fetchall()))
conn.commit()
conn.close()
Here is my Dockerfile:
FROM tiangolo/uwsgi-nginx:python3.7-alpine3.8
RUN apk update
RUN apk add gcc libc-dev g++ libffi-dev libxml2 unixodbc-dev
LABEL Name=code9 Version=0.0.1
EXPOSE 8000
ENV LISTEN_PORT=8000
ENV UWSGI_INI uwsgi.ini
WORKDIR /app
ADD . /app
RUN chmod g+w /app
RUN chmod g+w /app/db.sqlite3
RUN python3 -m pip install -r requirements.txt
我假设我是unixODBC将负责与Azure中的SQL服务器的连接或我是否需要为高山安装MS SQL驱动程序?有可用吗?我找不到一个。请帮忙。
确认设置:
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驱动程序。现在,找到司机
import pyodbc
pyodbc.drivers()
# []
Pyodbc无法找到它们,但它们肯定是已安装的,因此我们可以使用shell脚本找到它们:
find / -name *odbc.so
/usr/lib/libtdsodbc.so
/usr/lib/libodbc.so
现在,我们可以使用subprocess
库自动执行此操作以手动设置驱动程序位置:
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/odbcins.ini
,如here所述:
[FreeTDS]
Description=FreeTDS Driver
Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
然后
import pyodbc
pyodbc.drivers()
['FreeTDS']