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.
You can consider using pyodbc and
create_enginefrom 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: