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 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 following command in a terminal:
pip install pyodbc
or depending on your python installation:
python3 -m 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:
Here you have two files:
Open odbc.ini using the following command:
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:
Add the following lines to this file:
[MSSQL] Description = Test to SQLServer Driver = ODBC Driver 13 for SQL Server Trace = No Server = YourSQLServerAddress
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 terminal and enter your password:
sudo odbcinst -i -s -f ~/tempfile -l
To test your connection, open python editor and run the following script:
import pyodbc a=pyodbc.connect('DSN=MSSQL;UID=yourUserName;PWD=yourPassWord') print(a)
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>