Skip to content

Instantly share code, notes, and snippets.

@fastboatster
Forked from aaugustin/HOWTO.md
Created January 4, 2019 20:05
Show Gist options
  • Save fastboatster/f21d290a8a9c816b8b4d5716e2da6eda to your computer and use it in GitHub Desktop.
Save fastboatster/f21d290a8a9c816b8b4d5716e2da6eda to your computer and use it in GitHub Desktop.
Connecting a Django application to a Microsoft SQL Server database from Debian GNU/Linux
  1. Install and register the FreeTDS driver for unixODBC.

     apt-get install tdsodbc
     odbcinst -i -d -f /usr/share/tdsodbc/odbcinst.ini
    
  2. (Optional) Test the DSN-less connection with pyodbc.

     apt-get install python-pyodbc
    
     >>> import pyodbc
     >>> pyodbc.connect("DRIVER=FreeTDS;SERVER=...;PORT=1433;UID=...;PWD=...;DATABASE=...")
     <pyodbc.Connection object at ...>
    
     apt-get remove python-pyodbc
    
  3. In your project's virtualenv, install django-pyodbc.

     apt-get install python-dev unixodbc-dev
     # If you have an old version of pip:
     pip install django-pyodbc
     # If you have a recent version of pip:
     pip install --allow-external pyodbc --all-unverified pyodbc django-pyodbc
    
  4. Edit the DATABASES setting in your Django project.

     DATABASES = {
         '...': {
             'ENGINE': 'django_pyodbc',
             'NAME': '...',
             'HOST': '...',
             'PORT': 1433,
             'USER': '...',
             'PASSWORD': '...',
             'OPTIONS': {
                 'host_is_server': True,
             }
         }
     }
    
  5. Test the connection in ./manage.py shell.

     >>> from django.db import connection
     >>> cursor = connection.cursor()
     >>> cursor.execute("SELECT 2 + 2")
     <pyodbc.Cursor object at ...>
     >>> cursor.fetchall()
     [(4,)]
     >>> cursor.close()
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment