Python on MS SQL (via pyodbc)

I have been struggling, albeit not very long, to set up a DB connection to a remote MS SQL server through Python. I thought that the process is not as straight forward as I’d like it to be, but I guess that’s okay because as far as I can see the best solution is to cobble it together a bit.

Basically it seems that the best solution is not to use a python end to end module as a driver, but to use features that are available otherwise, such as ODBC. Then use a ODBC driver for the MS SQL engine and then use ODBC within Python.
As a Linux person, I first had to install unixodbc:

sudo apt-get install unixodbc unixodbc-dev

This takes care of you being able to use ODBC to connect to ODBC database servers. The other part is having a ODBC driver for the connection to the MS SQL server. There are probably others and I shall list them in due time, but for MS SQL, I found it easiest to use FreeTDS (an implementation of the Tabular Data Stream for Linux).

To install:

sudo apt-get install freedts-dev tdsodbc

With this done, you can preceed to modifying the /etc/odbcinst.ini:

sudo nano /etc/odbcinst,ini

[ODBC]
Trace = Yes
TraceFile = /tmp/odbc.log

[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
CPTimeout =
CPReuse =
UsageCount = 1

Please note that the paths for libtdsodbc.so and libtdsS.so are not necessarily as the ones given in this example. For one, I’m using a 64bit version, so on 32 the path is probably different. Another possible location for the files would be: /usr/lib/odbc/.
Either search for the location or seek Google to find where your distribution saves these files.

You will also need to have the python-dev stuff installed:

sudo apt-get install python-dev 

Now that the system is installed, you will want to install the pydobc module. You can download the latest version of the pyodbc module here. Extract the file where it’s convenient for you and ‘cd’ into the folder.
To install simply do:

sudo python setup.py install

Author: Chris A. Matenaers

Working in Digital Marketing, strong liberal world-views & privacy advocate. My hobbies are scuba-diving and coding. I'm also a huge Star Wars fan.

Leave a Reply

Your email address will not be published. Required fields are marked *