Sunday, 25 August 2013

Using Django with SQLServer

Microsoft SQLServer shouldn't be your first choice as a database for a Django project as support for it is limited.  If however you HAVE to use SQLServer, then I've had success with SQLServer 2008 using django-pyodbc:

To install django-pyodbc, download the following and save to c:\django-pyodbc:  https://github.com/avidal/django-pyodbc/zipball/django-1.4  

Run python setup.py install (from the django-pyodbc folder).

Ensure sqlserver folder exists within c:\django-pyodbc.  Add c:\django-pyodbc to the PYTHONPATH  system variable.  The PYTHONPATH should be as follows:  C:\PYTHON27;C:\PYTHON27\DLLs;C:\PYTHON27\LIB;C:\PYTHON27\LIB\LIB-TK;c:\django-pyodbc

Then add the following to settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': '<database_name>',                    
        'USER': '<username>',                     
        'PASSWORD': '<password>',                 
        'HOST':  r'<database server host name>',                      # Set to empty string for localhost.
          'DATABASE_ODBC_DSN': 'DSN name set up in Windows ODBC',
          'DATABASE_ODBC_DRIVER': 'SQL Server',
          'DATABASE_OPTIONS': {
            'driver': 'SQL Native Client',
               'MARS_Connection': True,
               }
     }
}

Replace <database_name> with the name of your database (you should create this using MySQL Workbench or from the MySQL command line first if it doesn't exist).

Replace <username> and <password> with the username and password required to access your MySQL database (use the MySQL Grant command to grant permissions to the user with the password).

Replace <database server host name> with the name of the machine hosting the MySQL database or leave this empty if the MySQL database is on your local machine. 


If you want to run Django on Linux connecting to SQLServer, then in my experience you may be in trouble.  django-pyodbc works to some extent on Linux, but I wouldn't recommend this combination.

No comments:

Post a Comment