Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading