0. 使用 docker 啟動MySQL數據庫
docker run -d -e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_DATABASE=sunk -p 3307:3306 --name test-mysql --restart always -v /home/ct/mysql1/data:/var/lib/mysql mysql:8.0.12 --default-authentication-plugin=mysql_native_passwor
注意:
1> 這里的“數據庫名“需要和下一步setting中的數據庫名一致!!
2> 我們的MySQL數據庫對外部應用程序(非 docker 容器)開放的端口號為: 3307
1. 在Django配置中選擇MySQL數據庫
在項目下的 setting.py
# Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sunk', 'USER':'root', 'PASSWORD':'123456', 'HOST':'127.0.0.1', 'PORT':'3307', } }
2. 安裝依賴包
2.1 在 python2 中,使用 mysql-python 進行安裝連接MySQL的庫
pip install mysql-python
如果大家使用的是python2, 我們的任務到此為止啦!!
如果是python3,請繼續看下文
2.2 在 python3 中,使用連接庫為 pymysql
pip install pymysql
3. 在項目目錄下的 __init__.py 中添加:
import pymysql pymysql.install_as_MySQLdb()
如下圖所示:

4. 重新啟動Django
python manager.py runserver
輸出如下:
Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. August 21, 2018 - 13:06:03 Django version 1.11.15, using settings 'DjangoProject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
Done,到此為止 Django 啟動正常,並且連接到MySQL數據庫 ~~
參考資料:
https://blog.csdn.net/u014360817/article/details/55504331
https://blog.csdn.net/lhyzyp/article/details/70550683
