Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect to SQL Server via sqlalchemy using Windows Authentication?

sqlalchemy, a db connection module for Python, uses SQL Authentication (database-defined user accounts) by default. If you want to use your Windows (domain or local) credentials to authenticate to the SQL Server, the connection string must be changed.

By default, as defined by sqlalchemy, the connection string to connect to the SQL Server is as follows:

sqlalchemy.create_engine('mssql://*username*:*password*@*server_name*/*database_name*') 

This, if used using your Windows credentials, would throw an error similar to this:

sqlalchemy.exc.DBAPIError: (Error) ('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for us er '***S\\username'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for us er '***S\\username'. (18456)") None None 

In this error message, the code 18456 identifies the error message thrown by the SQL Server itself. This error signifies that the credentials are incorrect.

like image 986
vbiqvitovs Avatar asked Jun 06 '14 15:06

vbiqvitovs


People also ask

How do I log into SQL Server with Windows Authentication?

Open SQL Server Management Studio. In Connect to Server, select Database Engine, enter your SQL Server name, and enter administrator credentials to connect to the server. Select Connect. In Object Explorer, expand the SQL Server, expand Security, right-click Logins, and then select New Login.

How do I configure Windows Authentication for SQL Server?

In SQL Server Management Studio Object Explorer, right-click the server, and then click Properties. On the Security page, under Server authentication, select the new server authentication mode, and then click OK.


1 Answers

In order to use Windows Authentication with sqlalchemy and mssql, the following connection string is required:

ODBC Driver:

engine = sqlalchemy.create_engine('mssql://*server_name*/*database_name*?trusted_connection=yes') 

SQL Express Instance:

engine = sqlalchemy.create_engine('mssql://*server_name*\\SQLEXPRESS/*database_name*?trusted_connection=yes')  
like image 70
vbiqvitovs Avatar answered Sep 21 '22 20:09

vbiqvitovs