简体   繁体   English

如何从 ZC5FD214CDD0D2B3B4272E 中的 python 容器脚本连接到 Ubuntu 上的本地 SQL 服务器

[英]How do I connect to the local SQL server on Ubuntu from a python script in Docker container

I have an SQL Server installed in Ubuntu 20.04 (which is installed in VirtualBox) and a Docker container with a python script in it. I have an SQL Server installed in Ubuntu 20.04 (which is installed in VirtualBox) and a Docker container with a python script in it. What I want to do is to connect from this python script to the SQL server running on the host.我想做的是从这个 python 脚本连接到主机上运行的 SQL 服务器。

Here is the Dockerfile I used to create an image:这是我用来创建图像的 Dockerfile:

# syntax=docker/dockerfile:1

FROM python:3.8-slim-buster
WORKDIR /app
COPY requirements.txt requirements.txt

RUN apt-get update && apt-get install -y gnupg2 curl
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list

RUN apt-get update
RUN ACCEPT_EULA=Y apt-get install -y msodbcsql17
RUN ACCEPT_EULA=Y apt-get install -y mssql-tools
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc

RUN apt-get update \
  && apt-get -y install gcc \
  && apt-get -y install g++ \
  && apt-get -y install unixodbc unixodbc-dev \
  && apt-get clean 

RUN pip3 install -r requirements.txt

COPY . .

CMD [ "python3", "-m" , "test", "run", "--host=0.0.0.0"]

I know it looks messy, but I encountered several issues while installing pyodbc, and it looks like all this code has solved the problem.我知道它看起来很乱,但是我在安装 pyodbc 时遇到了几个问题,看起来所有这些代码都解决了这个问题。

I can now successfully create an image, but when launching a container, it produces the following output:我现在可以成功创建映像,但是在启动容器时,它会生成以下 output:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/local/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/app/test.py", line 10, in <module>
    connection = pyodbc.connect(connection_string, autocommit=True)
pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
['ODBC Driver 17 for SQL Server']

It looks like there is something wrong with the connection string, which looks like this:连接字符串似乎有问题,如下所示:

connection_string = 'Driver={ODBC Driver 17 for SQL Server};Server=tcp:host.docker.internal,1433;UID=SA;PWD=<my_password>'

I've been struggling with this for some time now but still cannot make it work.我已经为此苦苦挣扎了一段时间,但仍然无法使其发挥作用。 Would appreciate any help or advice!将不胜感激任何帮助或建议!

UPD UPD

As Pato recommended, I tried changing the Server option in the connection string with the IP address of the machine.按照 Pato 的建议,我尝试使用机器的 IP 地址更改连接字符串中的Server选项。

ip addr show returned me the following output: ip addr show我返回了以下 output:

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:29:e8:b8 brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic noprefixroute enp0s3
       valid_lft 71149sec preferred_lft 71149sec
    inet6 fe80::2517:652e:ac69:8ec9/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:35:26:ba:86 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:35ff:fe26:ba86/64 scope link 
       valid_lft forever preferred_lft forever

So, I tried substituting host.docker.internal with 127.0.0.1 , 10.0.2.15 and 172.17.0.1 .所以,我尝试用127.0.0.110.0.2.15172.17.0.1替换host.docker.internal All of them gave me the following error:他们都给了我以下错误:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/local/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/app/test.py", line 10, in <module>
    connection = pyodbc.connect(connection_string, autocommit=True)
pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server;Server=tcp:172.17.0.1,1433;UID=SA;PWD=<my_password>' : file not found (0) (SQLDriverConnect)")

ifconfig returned me this: ifconfig给我返回了这个:

docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        inet6 fe80::42:35ff:fe26:ba86  prefixlen 64  scopeid 0x20<link>
        ether 02:42:35:26:ba:86  txqueuelen 0  (Ethernet)
        RX packets 25340  bytes 1240556 (1.2 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 39308  bytes 691001962 (691.0 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.2.15  netmask 255.255.255.0  broadcast 10.0.2.255
        inet6 fe80::2517:652e:ac69:8ec9  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:29:e8:b8  txqueuelen 1000  (Ethernet)
        RX packets 649701  bytes 946934508 (946.9 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 55603  bytes 7183567 (7.1 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 27675  bytes 49732911 (49.7 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 27675  bytes 49732911 (49.7 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

I was researching about this connection problem, and the error file not found is in this post .我正在研究这个连接问题,找不到错误文件在这篇文章中。 I tried to recreate your settings but I get the same error.我试图重新创建您的设置,但我得到了同样的错误。

A fast solution is to change the driver to pymssql==2.2.2 (tested in my docker container).一个快速的解决方案是将驱动程序更改为 pymssql==2.2.2(在我的 docker 容器中测试)。

pip3 install pymssql==2.2.2

Here's the example:这是示例:

import pymssql

conn = pymssql.connect('host.docker.internal', 'sa', 'yourPassword', "database")

cursor = conn.cursor()

cursor.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL
    DROP TABLE persons
CREATE TABLE persons (
    id INT NOT NULL,
    name VARCHAR(100),
    salesrep VARCHAR(100),
    PRIMARY KEY(id)
)
""")

cursor.executemany(
    "INSERT INTO persons VALUES (%d, %s, %s)",
    [(1, 'John Smith', 'John Doe'),
     (2, 'Jane Doe', 'Joe Dog'),
     (3, 'Mike T.', 'Sarah H.')])

# you must call commit() to persist your data if you don't set autocommit to True
conn.commit()

cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
row = cursor.fetchone()
while row:
    print("ID=%d, Name=%s" % (row[0], row[1]))
    row = cursor.fetchone()

conn.close()

# Result
'''
ID=1, Name=John Smith
'''

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Docker 容器中运行本地 Python 脚本? - How do I run a local Python script in a Docker container? 如何从Docker容器中的python脚本连接到localhost上的mysql数据库 - How to connect to a mysql database on localhost from a python script in a docker container 如何从在 docker 容器中运行的 python selenium 脚本在主机上打开 chrome? - How do I open chrome on the host from a python selenium script running in a docker container? 如何限制在docker容器中运行的ffmpeg的资源(从python脚本调用)? - How do I limit resources for ffmpeg, called from a python-script, running in a docker container? 如何从 dockerized python 应用程序连接到本地 sql server 数据库 - How to connect to local sql server database from dockerized python app SQL 服务器在 Macbook 上作为 docker 容器运行。 我无法连接到 python - SQL Server running as docker container on Macbook. I am unable to connect with python 如何从Ubuntu连接到Windows SQL Server - How to connect to windows SQL Server from Ubuntu 在Ubuntu服务器上,如何从Flask中的python脚本调用“ sudo reload myproject” - On an Ubuntu server, how do I call “sudo reload myproject” from a python script in Flask 如何从 docker 容器连接到本地 IIS 上的主机名? - How to connect to a hostname on local IIS from docker container? 如何使用Docker容器内的python套接字连接到服务器? - How can I connect to a server using python sockets inside a Docker container?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM