Connect SQL Server database to Django

Asked

Viewed 1,075 times

1

I have an SQL Server database that already exists, and I need to connect it to my project in Django.

So I come here to see if anyone has already found a solution to the problem, as they still can not solve it after several hours of research. thank you!

2 answers

2

First thing to do is install the package with Django backend for Azure and SQL Server:

pip install django-pyodbc-azure

Then in the Django settings file(Settings.py) look up the dictionary DATABASES and make the following change by providing the appropriate values to your application for NAME, USER, PASSWORD, HOST and PORT:

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'Nome do seu banco de dados',
        'USER': 'Nome do usuário',
        'PASSWORD': 'Senha',
        'HOST': 'Nome da instancia do SQL Server a ser utilizada',
        'PORT': 'Número da porta de comunicação',
    },
}

So just test the communication with the database.

  • 1

    It worked out! Thanks so much for your help!

  • @murilokrugner worth will mark the answer as accepted (see the pq)

0

I’d like to recommend the library Django-mssql-backend, for the official documentation follow the link:. https://pypi.org/project/django-mssql-backend/

It is the solution that I currently adopt for my personal and professional projects, never had problems with its use, the installation takes place by the following code:

pip install django-mssql-backend

OBS:. remember to carefully read the documentation, this is important!

Example( Settings.py ):

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'mydb',
        'USER': 'user@myserver',
        'PASSWORD': 'password',
        'HOST': 'myserver.database.windows.net',
        'PORT': '',

        'OPTIONS': {
            'driver': 'ODBC Driver 13 for SQL Server',
        },
    },
}

# set this to False if you want to turn off pyodbc's connection pooling
DATABASE_CONNECTION_POOLING = False

One of the dependencies is pyodbc in version 3.0 or higher, lib also supports regex, which I often use.

If you have problems with this lib, be aware that it is not due to the need to install an "ODBC DRIVER", this is more likely to occur in linux operating systems.

For more details just read the official documentation,

Good Luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.