Connect to SQL Server database by passing a different set of windows auth credentials in the python scripts

275 views Asked by At

I want to connect to a database by connecting as a different user using Python script and by using the Windows authentication method.

import pyodbc

server = 'server_name'  # Replace with your server name or IP address
database = 'database_name'  # Replace with your database name
trusted_connection = 'yes'  # Use 'yes' for Windows Authentication
password = r'password'
username = 'username'
try:
    connection = pyodbc.connect(f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}')

    
    cursor = connection.cursor()
    
    cursor.close()
    connection.close()
    # connection.close()

except pyodbc.Error as e:
    print("Error connecting to the database:", e)

When I run the script, it takes the current Windows credentials, and I want to pass different credentials so that I can access the instance

I was expecting to access this using different user cred, but when I run the scripts it uses the default Windows credentials.

1

There are 1 answers

9
Ifeoluwa On

You can consider using pyodbc and create_engine from sqlachemy, as this does not even require you to specify a password. I don't think it's safe putting plain text in a code:

import pyodbc
from sqlalchemy import create_engine

engine = create_engine('mssql+pyodbc://<server_name>/<database_name>?trusted_connection=yes&driver=SQL+Server+Native+Cleint+11.0')