【问题标题】:Issue connecting pyodbc to MS SQL database on Windows 10 Pro from WSL2 -> Ubuntu 20.04从 WSL2 -> Ubuntu 20.04 将 pyodbc 连接到 Windows 10 Pro 上的 MS SQL 数据库的问题
【发布时间】:2022-07-03 05:33:40
【问题描述】:

我有装有 Windows 10 的电脑。我安装了 Microsoft SQL Server 2019。下一步,我在 Windows 10 上安装了 WSL2 (Ubuntu 20.04)。 我尝试从 WSL2 (Ubuntu 20.04) 连接到 Windows 10 上的 MS SQL。

我已经尝试了所有我知道的和我发现的。以下是我尝试过但没有成功的两篇关于该主题的文章。

我在 Windows 防火墙中打开了 1433 端口,并尝试使用他,而不是在服务器和驱动程序的所有选项中使用。我尝试在服务器上使用五个选项,在驱动程序上使用两个选项,你可以在下面的代码中看到这个选项。我尝试编辑文件 /etc/hosts,在其中添加 IP 地址 172.29.176.1(它的操作在第二个链接中描述)

Connect to SQL Server on Windows from WSL2 with pyodbc - Connection Timeout

Connect to SQL Server running on Windows host from a WSL 2/Ubuntu sqlcmd

如果从 Windows 连接到 MS SQL,一切正常。

可能是什么问题,我做错了什么,我将不胜感激?!

import pyodbc
import pandas as pd
import socket

#server1 = f'{socket.gethostname()}.local'
#server2 = 'DESKTOP-2TUPNJK.local'
#server3 = '172.29.176.1' # this is IP-address WSL2 and this IP-address specified in WSL2 (Ubuntu 20.04) -> /etc/resolv.conf
#server4 = '192.168.1.4' # this is IP-address my PC on Windows 10
server5 = '127.0.0.1' # this is IP-address from /etc/hosts -> localhost

#driver1 = '{ODBC Driver 17 for SQL Server}'
driver2 = '/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1'

cnxn = pyodbc.connect('DRIVER=' + driver2 + ';SERVER='+server5+';PORT=1433;DATABASE=Test;UID=user;PWD=Password')  
df = pd.read_sql_query('SELECT name FROM sys.Tables', cnxn)
print(df)

我得到下一个错误:

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

【问题讨论】:

    标签: sql-server python-3.x ubuntu pyodbc wsl-2


    【解决方案1】:

    我设法解决了这个问题:

    首先 -> 服务器名称必须是您的 PC 的 IP 地址(Windows cmd 中的 ipconfig)

    第二步 -> 下一步按照这个instruction(我没有设置 -> ApexSQL 工具)

    这是我的代码:

    import pyodbc
    import pandas as pd
    
    cnxn = pyodbc.connect('DRIVER=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1;SERVER=192.168.0.2,1433;DATABASE=Test;UID=sa;PWD=Test')
    
    df = pd.read_sql_query('SELECT * FROM sys.Tables', cnxn)
    print(df)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 2022-07-10
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 2018-05-02
      • 1970-01-01
      相关资源
      最近更新 更多