我们使用Django来操作MySQL,实际上底层还是通过Python来操作的。因此我们想要用Django来操作MySQL,首先还是需要安装一个驱动程序。在Python3中,驱动程序有多种选择。比如有pymysql以及mysqlclient等。这里我们就使用mysqlclient来操作。mysqlclient安装非常简单。只需要通过pip install mysqlclient
常见的MySQL驱动介绍
MySQL-python
:也就是MySQLdb。是对C语言操作MySQL数据库的一个简单封装。遵循了Python DB API v2。mysqlclient
: 是MySQL-python的另外一个分支。支持Python3并且修复了一些bug。pymysql
: 纯Python实现的一个驱动。因为是纯Python编写的,因此执行效率不如MySQL-python。并且也因为纯Python编写的。因此可以和Python代码无缝衔接。在操作数据库之前,首先先要连接数据库。这里我们以配置MySQL为例来讲解。Django连接数据库不需要单独创建一个操作数据库文件,只需要使用Django内置的引擎就可以进行操作,在对应的settings.py
进行配置。
# databases : 为数据库引擎
# ps: 键必须都是大写
# name:数据库名字,user:用户,password:密码,HOST:地址值,POST:端口号
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_db1',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'POST': 3306,
}
}
在Django中操作数据库一般有两种方式:第一种为使用原生的mysql语句来进行操作。另外一种是使用ORM模型来操作。
在Django中使用原生sql语句操作其实就是使用Python db api
的接口来操作。如果你的mysql驱动使用的是pymysql,那么你就是使用pymysql来操作的,只不过Django将数据库连接的这一部分封装好了,我们只要在settings.py中配置好了数据库连接信息后直接使用Django封装好的接口就可以操作了。
app/views.py
from django.shortcuts import render
from django.http import HttpResponse
# 使用Django连接数据库
from django.db import connection
"""
纯Python连接mysql教程
cursor:游标
execute: 执行原生sql语句
fetchall: 展示所有的数据
"""
def index(request):
cursor = connection.cursor()
cursor.execute('select * from book')
# row = cursor.fetchone()
rows = cursor.fetchall()
print(rows)
return HttpResponse('这是首页')
views.py
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
# 导入数据库连接
# connection : 代表着连接的意思
from django.db import connection
# 创建游标
cursor = connection.cursor()
def index(request):
"""首页"""
cursor.execute("select * from book")
books = cursor.fetchall()
context = {
'books': books
}
return render(request, 'index.html', context=context)
def add_book(request):
"""添加图书"""
if request.method == "POST":
# 该get的name为form提交表单使用的book_name
# 要对应,否则提交不成功
name = request.POST.get('book_name')
author = request.POST.get('book_author')
cursor.execute("insert into book(`book_name`, `author`) values ('%s', '%s')" % (name, author))
return redirect(reverse('front:index'))
else:
return render(request, 'add_book.html')
def book_detail(request, book_id):
"""图书的详情页"""
cursor.execute("select * from book where id=%s" % book_id)
book = cursor.fetchone()
context = {
'book': book
}
return render(request, 'book_detail.html', context=context)
def book_delete(request, book_id):
if book_id:
cursor.execute("delete from book where id=%s" % book_id)
# reverser 反转为对应的路由的名字
return redirect(reverse('front:index'))
else:
return render(request, 'book_detail.html')
urls.py
# @Time : 2020/6/27 13:59
# @Author : SmallJ
from django.urls import path
from . import views
# 命名空间
app_name = 'front'
urlpatterns = [
path("", views.index, name='index'),
path("add_book/", views.add_book, name='add_book'),
path("book_detail//" , views.book_detail, name='book_detail'),
path('book_delete//' , views.book_delete, name='book_delete')
]
base.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<ul>
<li><a href="{% url 'front:index' %}">首页a>li>
<li><a href="#">发布图书a>li>
ul>
{% block content %}
{% endblock %}
body>
html>
add_book.html
{% extends 'base.html' %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
图书名字:<input type="text" name="book_name"><br>
图书作者:<input type="text" name="book_author"><br>
<input type="submit" value="提交">
form>
{% endblock %}
book_detail.html
{% extends 'base.html' %}
{% block content %}
<table>
<tr>
<th>序号th>
<th>图书名字th>
<th>图书作者th>
<th>操作/删除th>
tr>
<tr>
<td>{{ book.0 }}td>
<td>{{ book.1 }}td>
<td>{{ book.2 }}td>
<td><a href="{% url 'front:book_delete' book_id=book.0 %}">删除图书a>td>
tr>
table>
{% endblock %}
index.html
{% extends 'base.html' %}
{% block content%}
<ul>
<li><a href="{% url 'front:add_book' %}">添加图书a>li>
ul>
<table>
<tr>
<th>序号th>
<th>图书名字th>
<th>图书作者th>
tr>
{% for book in books %}
<tr>
<td>{{ forloop.counter }}td>
<td><a href="{% url 'front:book_detail' book_id=book.0 %}">{{ book.1 }}a>td>
<td>{{ book.2 }}td>
tr>
{% endfor %}
table>
{% endblock %}