【问题标题】:Trying to connect to SQL Server in Docker from external Python尝试从外部 Python 连接到 Docker 中的 SQL Server
【发布时间】:2020-05-31 10:16:04
【问题描述】:

我在https://www.youtube.com/watch?v=BVNWRYPv78o 之后创建了以下 Docker 映像:

docker pull microsoft/mssql-server-linux
docker run -d --name sql_server_name -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=YourPassword123' -p 1433:1433 microsoft/mssql-server-linux

现在我想尝试从本地 Python 脚本访问服务器。 关注https://stackoverflow.com/a/58088919/6131111 我愿意:

brew install unixodbc
brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
brew install msodbcsql17 mssql-tools

我的/usr/local/etc/odbcinst.ini 文件如下所示:

[ODBC Driver 17 for SQL Server]
Description=Microsoft ODBC Driver 17 for SQL Server
Driver=/usr/local/lib/libmsodbcsql.17.dylib
UsageCount=1

要了解我的服务器:

$ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' sql_server_name
172.17.0.2

在 python 脚本中,我将连接字符串创建为:

connection_string = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=172.17.0.2;DATABASE=WideWorldImportersDW;UID=sa;PWD=YourPassword123'

我之前已将 WideWorldImportersDW 导入我的数据库,如下所示:

但我得到了:

pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')

【问题讨论】:

  • 172.17.0.2 是实例在 Docker 虚拟网络中的 IP 地址。您的 -p 1433:1433 参数表明您已将 localhost 的 tcp/1433 端口映射到实例的 tcp/1433 端口,因此您的 Python 连接字符串(在 macOS 主机本身上运行)应该使用 ...;SERVER=localhost,1433;...

标签: python sql-server docker


【解决方案1】:

我使用本地 IP 地址作为服务器解决了这个问题:

connection_string = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=192.168.1.47,1433;DATABASE=WideWorldImportersDW;UID=sa;PWD=YourPassword123'

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多