Snippet: Connect MSSQL Database with Python

After testing several options to connect to a MSSQL database on a Raspberry PI through Python for a couple of jobs, the way it finally worked is using the FreeTDS driver through ODBC, using pyodbc.

Installation

sudo apt-get install freetds-dev python3
sudo pip3 install pyodbc

Code snippet

# Copyright Robert Eisele (https://www.xarg.org)
import pyodbc

conn = pyodbc.connect("DRIVER=FreeTDS;SERVER=192.168.0.1;PORT=1433;DATABASE=db_name;UID=user;PWD=password;TDS_Version=8.0;")
cursor = conn.cursor()
for row in cursor.execute("SELECT * FROM t1"):
    print(row)