我不确定我是否有您之前正在寻找的答案,因为您参考了 Microsoft ODBC 驱动程序 - 但是我将分享我为安装 UnixODBC 所做的工作(然后我将其与 PyODBC 模块一起使用与 MSSQL 数据库通信)。
以下是我使用过的命令的摘要(警告:未经测试,因为它们是从生产 Dockerfile 中剪切和粘贴的,我无法完整分享-):
假设您在基于 Debian/Ubuntu 的 Linux Docker 容器中
$ apt-get update
$ apt-get install python2.7 python-pip unixodbc unixodbc-dev freetds-bin freetds-dev tdsodbc nano
# nano is a text editor; Ctrl + O to write out, Ctrl + X to exit
$ nano /etc/odbcinst.ini
[FreeTDS]
Description = FreeTDS Driver for MSSQL
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
$ nano /etc/freetds/freetds.conf
[global]
# $Id: freetds.conf,v 1.12 2007-12-25 06:02:36 jklowden Exp $
#
# This file is installed by FreeTDS if no file by the same
# name is found in the installation directory.
#
# For information about the layout of this file and its settings,
# see the freetds.conf manpage "man freetds.conf".
# Global settings are overridden by those in a database
# server specific section
[global]
# TDS protocol version
tds version = 8.0
# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
;dump file = /tmp/freetds.log
;debug flags = 0xffff
# Command and connection timeouts
;timeout = 10
;connect timeout = 10
# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.
# Try setting 'text size' to a more reasonable limit
text size = 64512
# If you experience TLS handshake errors and are using openssl,
# try adjusting the cipher list (don't surround in double or single quotes)
# openssl ciphers = HIGH:!SSLv2:!aNULL:-DH
$ pip install pyodbc
$ nano test_database.py
import pyodbc
host = 'some.host.org'
port = 1433
username = 'some_username'
password = 'some_password'
conn_str = """
DRIVER={FreeTDS};
TDS_VERSION=8.0;
SERVER=%s;
Port=%i;
DATABASE=%s;
UID=%s;
PWD=%s;
""" % (
host, port, database, username, password
)
conn_str = conn_str.replace('\n', '').replace(' ', '')
connection = pyodbc.connect(conn_str, timeout=self._timeout)
connection.autocommit = True
cursor = connection.cursor()
cursor.execute('SELECT * FROM some_table;')
rows = cursor.fetchall()
for row in rows:
print row
cursor.close()
connection.close()
(上面的代码块是可滚动的)
我必须再次警告,这都是从我们的代码库中剪切和粘贴的,我还没有测试它现在出现的样子。
如果您无法访问 MSSQL 数据库进行测试,您可以使用以下命令将其启动为 Docker 容器(SQL Server Express Edition):
docker run -d --name mssql-server -p 1433:1433 -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=some_password' -e 'MSSQL_PID=Express' microsoft/mssql-server-linux:latest
另外请注意,作为上面安装的软件包的一部分,您将拥有“tsql”命令行工具,可用于在 Python 之外仔细检查您的数据库内容。
祝你好运!