I want to create trusted connections to a SQL Server database, using pymssql. Given that that code is going to be shared though, I don't want users entering their usernames, or passwords. I've found documentation that has conflicting information about how to achieve this.
What I want to be able to do is something like
engine = create_engine('mssql+pymssql://<Server>/<Database>?trusted=True')
Some things have said use trusted_connection=yes, others say use trusted=True. Neither of these options is working for me. Each time I try to use the engine I get an error saying that trusted
or trusted_connection
is an unexpected keyword argument.
I'm using SQLAlchemy version 1.0.9, and pymssql version 2.1.1.
PyODBC allows you connecting to and using an ODBC database using the standard DB API 2.0. SQL Alchemy is a toolkit that resides one level higher than that and provides a variety of features: Object-relational mapping (ORM) Query constructions.
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.
The create_engine() method of sqlalchemy library takes in the connection URL and returns a sqlalchemy engine that references both a Dialect and a Pool, which together interpret the DBAPI's module functions as well as the behavior of the database.
By passing the database which is not present, to the engine then sqlalchemy automatically creates a new database.
I just tested this on a Windows machine with
and it worked fine for me:
from sqlalchemy import create_engine
conn_str = r'mssql+pymssql://(local)\SQLEXPRESS/myDb'
engine = create_engine(conn_str)
connection = engine.connect()
result = connection.execute("SELECT SYSTEM_USER AS me")
row = result.fetchone()
print(row['me'])
And, even when the SQL Browser service was stopped on that machine, this connection string worked
conn_str = r'mssql+pymssql://localhost:52865/myDb'
So, at least on Windows machines, simply omitting the username and password will allow connections to the SQL Server via Windows authentication.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With