table of Contents
There are two ways to configure django project mysql database
1. Add database configuration information directly in the file settings.py
# 配置数据库的第一种方式
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'cheng_pro', # 数据库名称
'USER': 'cheng', # 数据库登录用户名
'PASSWORD': 'yanyan', # 密码
'HOST': '127.0.0.1', # 数据库主机IP, 默认为127.0.0.1
'PORT': 3306 # 数据库端口号 , 默认为3306
}
}
2. The configuration information is stored to a database file, which is incorporated in the settings.py file. (recommend)
New database configuration file mysql.cnf (random name) # configuration file as follows:
[client] database = cheng_pro user = cheng password = yanyan host = 127.0.0.1 port = 3306 default-character-set = utf8
References to use it in settings.py file
# 配置数据库的第二种方式 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 数据库引擎 'OPTIONS': { 'read_default_file': 'utils/dbs/mysql.cnf' # 读取数据库配置文件 } } }
Install mysql driver
1. mysqlclient * Recommended
pip install mysqlclient
pip install -i https://pypi.douban.com/simple mysqlclient # 使用douban源安装
If the installation mysqlclient error, you need to install the dependent mysqlclient: default-libmysqlclient-dev
sudo apt update # 先更新软件包列表
sudo apt install default-libmysqlclient-dev # 安装依赖
2. Use pymysql django2.2 above default does not support the use of the
Installation pymysql, and requires its own package file settings.py __init__.py
introduced pymysql
pip install -i https://pypi.douban.com/simple pymysql
import pymysql
pymysql.install_as_MySQLdb()