Skip to content

Instantly share code, notes, and snippets.

@cwade
Last active August 28, 2023 15:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwade/9a15b96821dc18cde0ef7ddcc2940c1d to your computer and use it in GitHub Desktop.
Save cwade/9a15b96821dc18cde0ef7ddcc2940c1d to your computer and use it in GitHub Desktop.
Using Python to connect to a Microsoft SQL Server database from OS X using Windows authentication

There are many instructions out there on how to do this, but none quite worked for me. I'm currently on a Mac running OS X Mojave (10.14.4)

These instructions got me closest, but I still couldn't get the python part of the equation to work.

Here's what worked for me.

First, install unixodbc using Homebrew. I highly recommend using Homebrew here because it's a little more complicated to install on its own.

brew install unixodbc

Then install pyodbc using pip (pip3 in my case)

pip3 install pyodbc

Now you need a driver to connect to SQL Server. I tried FreeTDS and Microsoft® ODBC Driver 17 for SQL Server® to no avail. I kept getting errors like "The login is from an untrusted domain and cannot be used with Integrated authentication." While monkeying around for hours though, I noticed my machine already had a different driver called simba installed. After poking around, I learned that simba is the driver that Tableau uses to connect to a SQL Server database. Since I had successfully connected Tableau to the database in question, I knew it could be done. If you don't already have Tableau installed, and I suspect most are in this boat, you can download the drivers here. This link currently works for me for a direct download.

Even then, it wasn't an easy connection. For some reason, I could never get my configuration to work using a DSN from a odbc.ini configuration file, but I was able to connect using a connection string from Python, using pyodbc, as follows:

import pyodbc as p
a = p.connect('Driver=/Library/simba/sqlserverodbc/lib/libsqlserverodbc_sbu.dylib; Server=MY-SERVER-NAME.DOMAIN.COM; Database=THE_DB_NAME; UID=MY_DOMAIN\\USERNAME; PWD=mypassword; Integrated Security=NTLM')

The "Integrated Security=NTLM" piece seems to be key, but like I said, for some reason I couldn't get this to work from a odbc.ini file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment