MS SQL on MacOS: Connect to your database using Python

1 minute read

In this article series, I’ll review the tools and options to connect to an MS SQL server on macOS.

Table of contents:

Microsoft has released a beta version of its ODBC driver for macOS. Here is a quick and easy guide to connecting to your MS SQL using python.

The first thing you need is to install Homebrew.

Enter the following command in a terminal window to install Homebrew:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Afterward, enter the following commands in a terminal window to install Microsoft ODBC driver 13 for macOS:

brew tap microsoft/msodbcsql https://github.com/Microsoft/homebrew-msodbcsql-preview
brew update
brew install msodbcsql

Next item you need to install is pyodbc by entering the following command in a terminal:

pip install pyodbc

Now you have all the prerequisites to connect to your MS SQL database in python.

Now navigate to unixodbc folder using the following command:

cd /usr/local/Cellar/unixodbc/2.3.4

Here you have two files:

1-odbc.ini

2-odbcinst.ini

Open odbc.ini using the following command:

nano odbcinst.ini

There you will see the following information:

[ODBC Driver 13 for SQL Server]
Description=Microsoft ODBC Driver 13 for SQL Server
Driver=/usr/local/lib/libmsodbcsql.13.dylib
UsageCount=1

You need the copy the content in the square brackets which in my case is “ODBC Driver 13 for SQL Server”.

Exit the editor and open a new file like this:

nano ~/tempfile

Add the following lines to this file:

[MSSQL]
Description = Test to SQLServer
Driver = <strong>ODBC Driver 13 for SQL Server</strong>
Trace = No
Server = <strong>YourSQLServerAddress</strong>

Replace “ODBC Driver 13 for SQL Server” with the content you copied in the square brackets. Also, write your SQL server address instead of “YourSQLServerAddress“. Save the file and exit Nano editor.

Now, enter the following command in the terminal and enter your password:

sudo odbcinst -i -s -f ~/tempfile -l

To test your connection, open python editor and run the following script:

DSN is the name you used in the temp file. Replace yourUserName and yourPassWord with the ones you use for your SQL server.

You will see an output similar to:

<pyodbc.Connection object at 0xfffffffff>