文章目錄
操作數據庫
MySQL驅動程序安裝
我們使用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 Connector/Python : MySQL官方推出的使用純Python連接MySQL的驅動。因爲是純Python開發。效率不高。
Django配置連接數據庫
在操作數據庫之前,首先先要連接數據庫。這裏我們以配置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中操作數據庫
在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('這是首頁')
圖書管理系統
首頁/index.html
添加圖書/add_book.html
刪除圖書/book_detail
App/front
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/<int:book_id>/", views.book_detail, name='book_detail'),
path('book_delete/<int:book_id>/', views.book_delete, name='book_delete')
]
模板文件
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</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">
<!-- 在Django中提供了一個表單驗證,就是csrf_token安全驗證-->
{% 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 %}