Saturday, January 24, 2015

Using django-pyodbc to Connect to MS SQL Server Database on Ubuntu


Django doesn't officially support Microsoft SQL Server. To connect to SQL Server in your Django projects, you can use django-pyodbc as the DB backend.

1. Install required packages on your Ubuntu server:

sudo apt-get install unixodbc unixodbc-dev freetds-dev tdsodbc

In the virtualenv of your django project, install pyodbc and django-pyodbc:

pip install --allow-external pyodbc --allow-unverified pyodbc pyodbc
pip install django-pyodbc 
 
2. Edit /etc/freetds/freetds.conf to update the server for SQL Server .

# A typical Microsoft server
[sqlserver]
        host = <server ip>
        port = 1433
        tds version = 7.0


3. Set up FreeTDS driver in etc/odbcinst.ini (Run odbcinst -j to check where the configuration files are located and make sure the paths for the Driver and Setup are valid):

[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 =
FileUsage = 1

4. Update the DATABASES setting for your django project:

DATABASES = { 
     'default': {
         'ENGINE': "django_pyodbc", 
         'HOST': "sqlserver", 
         'USER': "mssql_user", 
         'PASSWORD': "mssql_password", 
         'NAME': "database_name", 
         'OPTIONS': {
             'host_is_server': False, 
             'driver': 'FreeTDS', 
         }, 
     } 
}

5. Test your connection and celebrate.