Django使用MySql数据库

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

原文地址:https://www.cnblogs.com/atuotuo/p/9514409.html