Jango Mac OS

Some projects require a MSSQL database (either legacy or for other reasons). Unfortunately Django doesn't officially support this database (yet).

In this tutorial we will show how to connect to MSSQL from Python/Django using pyodbc.

Installing on Mac OS X

All the codes of the Django framework are written in Python, which runs on many platforms. Which leads to run Django too in many platforms such as Linux, Windows and Mac OS. Installation of Django. Install python3 if not installed in your system ( according to configuration of your system and OS) from here. Try to download the latest version of. Django is written in Python, which runs on many platforms. That means that you are not tied to any particular server platform, and can run your applications on many flavours of Linux, Windows, and Mac OS X.

First of all we must install two dependencies: freetds and libiodbc. Let's use MacPorts for this (http://www.macports.org/). The MacPorts Project is an open-source community initiative to design an easy-to-use system for compiling, installing, and upgrading either command-line, X11 or Aqua based open-source software on the Mac OS X operating system.

Jango Mac Os X

Now we have to install pyodbc and django-pyodbc (in your virtualenv of course!)

When everything is ready we can set up odbc. To do this open ODBC Manager -> Drivers -> Add… and enter this data (change path if needed):

Driver Name: FreeTDS
Driver file: /opt/local/var/macports/software/freetds/0.82_0/opt/local/lib/libtdsodbc.so

It appears as if the system stores ODBC configuration data in /Library/ODBC, but the Mac Ports stores configuration in /opt/local/etc. So lets do some symlinks:

Jango Mccormick

That's it!

Installing on Ubuntu

First of all we must install two dependencies: freetds and libiodbc.

Then we install pyodbc and django-pyodbc:

When we have all in place, we must set up odbc. To do this edit odbcinst.ini file (change path if needed):

sudo vim /etc/odbcinst.ini

and paste this configuration:

You are ready to use MSSQL now!

Django Settings

Jango

Last step is proper settings file. Here is an example:

Most important are ENGINE and OPTIONS.

'ENGINE' should be set to 'sql_server.pyodbc'
'driver' name is a name used in odbc configuration.
If you use remote db, you must use `'host_is_server': True` parameter.
Last important param is 'TDS_VERSION=8.0'. We must declare TDS protocol version.

After all these steps, you should be able to connect MSSQL successfully.

Troubleshooting

You might encounter an error when trying to read Decimal fields: MemoryError of fetching results. – on Mac OS X
HY003 Program type out of range (SQLGetData() ) when trying read numerical field (MSSQL) – on Ubuntu

It seems that problem was fixed by wesm at github: https://github.com/wesm/pyodbc/tree/getdata-decimal-bug

When you update pyodbc with this build (pyodbc 2.1.10-beta04) problems should dissapear! Hope this post was helpful and saved you some development time.