Connecting to Microsoft SQL Server in Python

Question:

I’m currently running into the issue of being unable to connect to the a microsoft sql server database through python that I can connect to via Tableau. I’m attempting to track some historical data that we cannot keep within our database for future years. This uses windows authentication and I’ve confirmed it working from my local machine to the server in Tableau. However, I’m not sure what driver Tableau uses in order to make this connection. I have tried to connect via ODBC in Tableau and run into the same issue as I do in python.

   import pyodbc
   cnxn_write = pyodbc.connect(driver='{SQL Server}',
                            server='FQDN, Port NumberSQLEXPRESS',
                            database='DataAnalytics',
                            trusted_connection='yes'
                           )

Returns the following error code

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
C:UsersUserAppDataLocalTemp/ipykernel_6969/555555555.py in <module>
      3 import pyodbc
      4 import date
time
----> 5 cnxn_write = pyodbc.connect(driver='{SQL Server}',
      6                             server='server-nameSQLEXPRESS',
      7                             database='DataAnalytics',

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

The following code returns the same error.,

    import pyodbc
    cnxn_write = pyodbc.connect(driver='{SQL Server}',
                            server='FQDN, Port Number',
                            database='DataAnalytics',
                            trusted_connection='yes'
                           )

Anyone have any thoughts on what driver I should be using to attempt to connect with this database? I’ve tried {SQL Server} and {ODBC Driver 17 for SQL Server}. Or is this more likely to be on the server side than on my end?

Thanks everyone!

Answers:

So in case anyone else runs into this issue in the future. pyodbc was not properly connecting to the driver ODBC Driver 17 for SQL Server. My fix was creating a User DSN after running the Windows executable odbcad32.exe. That properly identified the server, credentials and mirror server for the database. I called this User DSN ‘sqlexpress’ and the following is my connect string now.

cnxn_write = pyodbc.connect(r'DSN=sqlexpress')

Sadly this feels more like a workaround than a solution, but it now properly connects to my database.

I had the same problem but this worked for me. I use mssql

import pymssql  
conn = pymssql.connect(server='host:port', user='user', password='pass', database ='database')

#%%

cursor = conn.cursor()  
cursor.execute('SELECT TOP 10 * from table;')  
row = cursor.fetchone()  
while row:  
    print(str(row[0]) + " " + str(row[1]) + " " + str(row[2]))     
    row = cursor.fetchone()
Answered By: Rodrigo Peña