一、安装

1. 安装mysql

windows下推荐下载phpstudy,一键安装,具体操作百度:phpstudy 安装教程

安装时记下数据库登陆的账号密码。

安装成功之后,如下

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_数据库

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_02

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_django_03

请先确保mysql的版本大于5.6,如果不大于,在django会报错,需要升级mysql,一切都没有问题之后,

新建一个数据库,名字叫visit_tsinghua,编码一定要选择utf8-general-ci,否则不支持中文存储

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_django_04

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_05


2. 安装mysqlclient2.0.3

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_06

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_07

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_08

安装成功之后,在外面可以看到

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_django_09


二、在Django框架里使用mysql

1.  在settings.py中修改DATABASES内容如下:


【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_django_10

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'visit_tsinghua',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': '3306',
'OPTIONS': {
"init_command": "SET sql_mode='STRICT_TRANS_TABLES'",
}
}
}

其中NAME是你的数据库名称,HOST是数据库地址,其它的大家都知道。


2. 进入models.py中创建与你的数据库表相对应的对象model

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_11

from django.db import models


class User(models.Model):
id = models.AutoField(primary_key=True) # django 在每一次save()操作后都可以正常的增加一条数据并且id顺序自增。id无需在save中创建,数据表自动添加
name = models.CharField(max_length=50)
level = models.IntegerField(default=1) # 用户等级,默认1
createTime = models.DateTimeField(null=True)

class Meta:
db_table = 'User' # 数据表名称

命令行中进入 manage.py同级目录


执行python manage.py makemigratetions app名(可选)

# 让 Django 知道我们在我们的模型有一些变更
python manage.py makemigrations userWeb

再执行

# 创建表结构
python manage.py migrate

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_12

查看数据库,发现已经新建了user表了。

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_django_13

这叫ORM,对象关系映射(Object Relation Mapping),实现对象和数据库的映射,隐藏数据访问的细节,不需要编写SQL语句


在models.py中可以创建多个表的model。


3. 在admin.py中注册model

from django.contrib import admin
from . import models

# Register your models here.
admin.site.register(models.User)

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_数据库_14



4. 其中testUser.html是放在templates中的前端页面:

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_15

<!DOCTYPE html>
<html>
<body>
<p>请输入用户信息</p>
<form action="/testadduser" method="post">
{%csrf_token%}
姓名: <input type="text" name="name"> <br>
用户等级: <input type="number" name="level"> <br>
<input type="submit" value="提交">
</form>
</body>
</html>




5. views.py(或者自己创建的py文件)中编写代码主要看 testAddUser 这个方法:

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_16

import datetime

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from userWeb.models import User


def index(request):
return render(request, './userWeb/index.html')

# 加法页面
def add(request):
return render(request, './userWeb/add.html')

# 执行加法
def doadd(request):
a = request.POST['a']
b = request.POST['b']
a = int(a)
b = int(b)
result = a + b
# return HttpResponse(str(result))
context = {}
context['a'] = a
context['b'] = b
context['result'] = result
return render(request, './userWeb/add_result.html', context)

# 增加用户页面
def testUser(request):
return render(request, './userWeb/testUser.html')

def testAddUser(request):

name = request.POST['name']
level = request.POST['level']
createTime = datetime.datetime.now()

user = User.objects.create(name=name, level=level, createTime=createTime)

context = {}
context['msg'] = '用户新增成功'
context['数据库中的id'] = user.id
return HttpResponse(str(context))

create操作的返回值,user.id表示此条数据在数据库中的id

6.到urls.py中添加路径完整代码如下:

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_django_17

"""visit_tsinghua URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from userWeb.views import *

urlpatterns = [
path('admin/', admin.site.urls),
path('index', index),
path("add", add),
path("doadd", doadd),
path("testuser", testUser),
path("testadduser", testAddUser),
]


7. 运行效果

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_18

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_19

【Django 2021年最新版教程8】操作Mysql数据库 mysqlclient安装和使用_html_20