Django: Unable to connect to Microsoft SQL Server

心不动则不痛 提交于 2019-12-08 02:48:06

问题


I am unable to connect to the MS SQL server using Django (Version- 1.11.3)

Here is the error, I seem to be getting:

django.db.utils.OperationalError: ('08001', u'[08001] [unixODBC][FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)')

This is the odbcinst.ini file:

 [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=2

This is the django settings.py snippet:

DATABASES = {
    'mssql': {
        'ENGINE':'sql_server.pyodbc',
        'NAME': '<NAME>',
        'USER': '<USER>',
        'PASSWORD':'<password>',
        'HOST':'<host-id>',
        'OPTIONS':
        {
            'driver':'FreeTDS'
        }
    }
}

回答1:


A few things:

  • You'll need to set the connection name as default instead of mssql
  • If you're using FreeTDS on Linux, I'd recommend using the django-pyodbc-azure Django DB engine: pip install 'django-pyodbc-azure>=1.11,<2'
  • You'll need to specify the TDS Verison in your settings.

The upshot of this will be settings like this:

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': '<NAME>',
        'USER': '<USER>',
        'PASSWORD':'<password>',
        'HOST':'<host-id>',
        'PORT': '1433',
        'OPTIONS': {
            'driver': 'FreeTDS',
            'unicode_results': True,
            'host_is_server': True,
            'extra_params': 'tds_version=7.3',
        }
    }
}

For windows:

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': '<NAME>',
        'USER': '<USER>',
        'PASSWORD':'<password>',
        'HOST':'<host-id>',
        'PORT': '1433',
        'OPTIONS': {
            'driver': 'ODBC Driver 13 for SQL Server',
        }
    }
}

You can see the django-pyodbc-azure docs for 1.11 here: https://github.com/michiya/django-pyodbc-azure/tree/azure-1.11

Good luck! These settings can be tricky for SQL Server, but once you get them right, it works well.




回答2:


I had the same issue while working on Windows 10 and here's what worked for me: Download the driver from here: https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-2017 And then add 'driver': 'ODBC Driver 17 for SQL Server', to Options in settings.py I hope it helps.



来源:https://stackoverflow.com/questions/50370563/django-unable-to-connect-to-microsoft-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!