Detailed explanation of Python Django switching MySQL database instance
- 2021-07-18 08:29:48
- OfStack
Prepare
软件 | 版本 |
---|---|
Django | 2.1.3 |
Python | 3.7.1 |
sqlite3 is used by default
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Switch to MySql:
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'book',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'POST': '3306',
}
}
Implementation steps
We use Django to operate MySQL, but actually the bottom layer is operated through Python. Therefore, if we want to operate MySQL with Django, we still need to install a driver first. In Python3, there are many choices of drivers. For example, there are pymysql and mysqlclient.
Introduction to common Mysql drivers:
MySQL-python: That is, MySQLdb. Is a simple encapsulation of MySQL language operating MySQL database. Follow Python DB API v2. However, only Python2 is supported, and Python3 is not supported at present. mysqlclient: is another branch of MySQL-python. Supports Python3 and fixes 1 bug. pymysql: One driver implemented by pure Python. Because it is written in pure Python, it is not as efficient as MySQL-python. And because it is written in pure Python, it can be seamlessly connected with Python code. MySQL Connector/Python: MySQL official driver using pure Python to connect MySQL. Because it was developed by pure Python. The efficiency is not high.
mysqlclient Installation
Based on the current environment and version, running pip install mysqlclient directly will report errors. Specific errors will be known by executing the following.
Solution:
Go to https://www. lfd. uci. edu/~ gohlke/pythonlibs/# mysqlclient to download the specified file. I used python3.7 and the win environment is 64 bits, so I downloaded mysqlclient-1. 3.13-cp37-cp37m-win_amd64. whl.
Then execute:
pip3 install mysqlclient-1.3.13-cp37-cp37m-win_amd64.whl
If the following instructions appear, the installation is successful:
Installing collected packages: mysqlclient
Successfully installed mysqlclient-1.3.13
To migrate a database
In Django, the database is migrated with the following command, which is executed each time Model is created to generate the corresponding table in the database:
python manage.py makemigrations
python manage.py migrate