SoFunction
Updated on 2024-11-16

Django connection sql server database method

*I would like to note that I am using python 3.5 and Django 2.0.4.

sql server is a closed source relational database from Microsoft that runs on windows and linux platforms. Because of its closed source characteristics, so fewer companies use it, but more amazingly, the company I work for and the company of several of my friends are crawler-based business, are to use sql server as the main database in use.

I. Packing

If you are using Django veterans should know that Django does not support sql server by default; if you are just starting to contact Django, then you should know that Django supports four databases by default: postgresql, mysql, oracle, sqlite. the above four databases do not need to directly carry out too much operation, only You need to modify the project file in the DATABASE on it.

But with sql server, you need to import some more stuff yourself.

 

The packages involved in the above picture are the ones I typed in myself, all of which can be installed via "pip install XXX", and do not need to be imported in the Django file. In particular, django-pyodbc-azure must be installed, without it directly crash.

II. Codes

Once you have completed the previous step you will only need to modify the files in your project.

DATABASES = {
  'default': {
    'NAME': 'screen',
    'ENGINE': 'sql_server.pyodbc',
    'HOST': '127.0.0.1',
    'PORT': '1433',
    'USER': 'user',
    'PASSWORD': 'password',
    'OPTIONS':{
      'driver':'SQL Server Native Client 10.0',
    }
  }
}

There are a few things to keep in mind here:

1. The key-value pair 'ENGINE' is written in a fixed way (it seems to take effect only after pip install pyodbc, it's been a bit long, I can't remember a bit)

The default port number for server is 1433, but some companies may change the port number, so you'd better check if the port is occupied by sql server before you use it.

3. In the connection of the default database when many people have not written 'OPTIONS' this thing, I did not write at the beginning, the results of how to connect. After checking the Internet, a lot of people say in odbc to adjust the database something engine (the company used windows as a development system, do not spray ......). As a result, add in or not, and finally found that 'OPTIONS' is not written, after writing all the problems are solved.

This is also something I did a long time ago and just got free to start organizing it, so there are some things that may have been missed. If anyone reading this finds some errors or omissions please leave a comment and I'll correct them promptly. Thank you! I hope this article can help those who need help! I also hope that you will support me more.