michiya / django-pyodbc-azure

Django backend for Microsoft SQL Server and Azure SQL Database using pyodbc
https://pypi.python.org/pypi/django-pyodbc-azure
BSD 3-Clause "New" or "Revised" License
321 stars 140 forks source link

connection string formatting #201

Open emiliajin opened 5 years ago

emiliajin commented 5 years ago

Since I now test in django 2.1 environment, I use django-pyodbc-azure 2.1.0.0.

I write my connection string as follow: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'XXX', 'USER': 'XXX', 'PASSWORD': 'XXX', 'HOST': 'XXX\SQLEXPRESS', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } }

This connection string works fine under django 1.11.8 and django-pyodbc-azure 1.11.0.0.

However, in django 2.1 I will get the error: ('08001', '[08001] [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: No connection could be made because the target machine actively refused it.\r\n (10061) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 13 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (10061)')

I check the connection string that parse to pyodbc,

in django-pyodbc-azure 1.11.0.0, this setting will be configure to 'DRIVER=ODBC Driver 13 for SQL Server;PORT=1433;SERVER=XXX\SQLEXPRESS;UID=XXX;PWD=XXX;DATABASE=XXX;MARS_Connection=yes'

in django-pyodbc-azure 2.1.0.0, this setting will be configure to 'DRIVER=ODBC Driver 13 for SQL Server;SERVER=XXX\SQLEXPRESS,1433;UID=XXX;PWD=XXX;DATABASE=XXX;MARS_Connection=yes'

which will cause the error, I guess when using XXX\SQLEXPRESS in local testing, 'XXX\SQLEXPRESS,1433' is not valid.

tartieret commented 5 years ago

Have you solve this issue? According to the Microsoft documentation, the connection string generated by django-pyodbc-azure is valid. It even works if I test with a online database with the connection string being:

DRIVER=ODBC Driver 17 for SQL Server;SERVER=<my server name>.database.windows.net,1433;UID=username;PWD=password;DATABASE=databasename;MARS_Connection=yes

However, on localhost the format does not seem to be valid with "SERVER=localhost\SQLEXPRESS,1433"

I found a workaround. You can declare the port number in the "extra_params" so that it will be added at the end of the connection string.

The Django configuration for your local development is then:

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'HOST': 'localhost\SQLEXPRESS',
        'NAME': 'databasename',
        'USER': 'username',
        'PASSWORD': 'password',
        'OPTIONS': {
                'driver': 'ODBC Driver 17 for SQL Server,
        },
        'extra_params': 'PORT=1433'
    }
}