Issue
I have pc with Windows 10. I installed Microsoft SQL Server 2019. Next action, on Windows 10 I installed WSL2 (Ubuntu 20.04). I try to connect from WSL2 (Ubuntu 20.04) to MS SQL on Windows 10.
I have tried everything I know and what I have found. Below are two articles on the subject that I have tried with no success.
I opened the 1433 port in Windows Firewall, and tried use him and not in all options with server and driver. I tried use five options with server and two options with driver, you can see this options in code bellow. I tried edit file /etc/hosts, where I add IP-address 172.29.176.1 (it action describe in second link)
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
If connect to the MS SQL from Windows everything works.
What could be the problem, what am I doing wrong, I will be grateful for the help?!
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)
I get next error:
pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
Solution
I managed to solve this issue:
First -> the server name must be the IP address of your PC (ipconfig in Windows cmd)
Second -> next step follow this instruction (I didn't set up -> ApexSQL tools)
And this is my code:
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)
Answered By - Aleksandr Answer Checked By - Candace Johnson (WPSolving Volunteer)