1、安装pymysql,因为python3没有mysqldb包
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pymysql
2、在settings.py同目录下的__init__.py中添加下面内容:
import pymysql
pymysql.install_as_MySQLdb()
3、将settings里面的DATABASES改成MySQL相关
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'person', # 数据库名称
'USER': 'root', # 数据库用户名
'PASSWORD': '123456', # 数据库密码
'HOST': '127.0.0.1', # 数据库IP
'PORT': '3306' # 数据库端口,MySQL默认为3306
}
}
4、models.py代码如下,为了测试连接~
from django.db import models # Create your models here. class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.name
5、同步数据库,1.8以上的版本用下面两条命令:
python manage.py makemigrations
python manage.py migrate
可以得到如下结果:
E:\Learn\Program\ShuHaiShiYi>python manage.py makemigrations
Migrations for 'Linux_150_CMD':
Linux_150_CMD\migrations\0001_initial.py:
- Create model Person
E:\Learn\Program\ShuHaiShiYi>manage.py migrate
Operations to perform:
Apply all migrations: Linux_150_CMD, admin, auth, contenttypes, sessions
Running migrations:
Applying Linux_150_CMD.0001_initial... OK
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK
本篇就先介绍到这里,感谢大家的支持,咱们下期再见咯。