Search code examples
pythonpyodbc

Connect to SQL database using windows authentication


I have a SQL database on my computer that I am trying to connect to using python. For starters, when I connected to the database with SQL Server Management Studio, I used the option connect with windows authentication. Now I am trying to connect to it the same way with python. Here is the code I have

import pyodbc
cnxn = pyodbc.connect(r'Driver={SQL Server};Server=localhost; \
                      Database=fatigue_life_test_db;Trusted_Connection=yes;')
cursor = cnxn.cursor()

cnxn.close()

The second line is throwing the following error:

pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (5); [08001] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)')

I also tried replacing the localhost with the name of the server (MSSQLSERVER) but it still gives the same error. I am quite new to SQL databases so there is probably something obvious that I'm missing here. I couldn't find a way to solve this issue even with an extensive googles search.


Solution

  • You can resolve this issue by following point:

    1. Verify SQL Server Instance name: localhost or local
    2. Check SQL Server service is running or not.
    3. Make sure TCP/IP protocol is enabled. if not you can do via SQL server confiiguration manager.
    4. Check windows firewall settings are not blocking your SQL Server instance.
    5. Write this code and check again:
    import pyodbc
    
    try:
        cnxn = pyodbc.connect(
            r'Driver={SQL Server};'
            r'Server=localhost,1433;'  # Assuming the default port 1433
            r'Database=fatigue_life_test_db;'
            r'Trusted_Connection=yes;'
        )
        cursor = cnxn.cursor()
        print("Connection established.")
    except pyodbc.Error as e:
        print("Error in connection:", e)
    finally:
        if 'cnxn' in locals() and cnxn:
            cnxn.close()