Django03:数据库

MySQL数据库安装:

  1. 在MySQL的官网下载MySQL数据库安装文件:https://dev.mysql.com/downloads/windows/installer/5.7.html。
  2. 然后双击安装,如果出现以下错误,则到http://www.microsoft.com/en-us/download/details.aspx?id=17113下载.net framework。

操作数据库

在操作数据库之前,首先先要连接数据库。这里我们以配置MySQL为例来讲解。Django连接数据库,不需要单独的创建一个连接对象。只需要在settings.py文件中做好数据库相关的配置就可以了。示例代码如下:

DATABASES = {
    'default': {
        # 数据库引擎(是mysql还是oracle等)
        'ENGINE': 'django.db.backends.mysql',
        # 数据库的名字
        'NAME': 'dfz',
        # 连接mysql数据库的用户名
        'USER': 'root',
        # 连接mysql数据库的密码
        'PASSWORD': 'root',
        # mysql数据库的主机地址
        'HOST': '127.0.0.1',
        # mysql数据库的端口号
        'PORT': '3306',
    }
}

在这里插入图片描述
在这里插入图片描述

在Django中操作数据库:

# 使用django封装好的connection对象,会自动读取settings.py中数据库的配置信息
from django.db import connection

# 获取游标对象
cursor = connection.cursor()
# 拿到游标对象后执行sql语句
cursor.execute("select * from book")
# 获取所有的数据
rows = cursor.fetchall()
# 遍历查询到的数据
for row in rows:
    print(row)
from django.shortcuts import render
from django.db import connection


def index(request):
    # Django 使用原生sql语句操作数据库
    # 下面的方法没有提示
    cursor = connection.cursor()
    # 插入语句
    # cursor.execute("insert into book(id,name,author) values (null,'术士回战','日本漫画')")
    # 查找数据
    cursor.execute("select id,name,author from book")
    rows = cursor.fetchall()
    for row in rows:
        print(row)
    # (1, '三国演义', '罗贯中')
    # (2, '术士回战', '日本漫画')

    return render(request, 'index.html')

图书管理案例

from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
from django.db import connection

# Create your views here.

def get_corsor():
    return connection.cursor()


def index(request):
    cursor = get_corsor()
    cursor.execute("select id,name,author from book")
    books = cursor.fetchall()
    # 返回 列表数据

    return render(request,'index.html', context={"books":books})


# 发布图书
def add_book(request):
    if request.method == 'GET':
        return render(request,'add_book.html')
    else:
        name = request.POST.get("name")
        author = request.POST.get("author")
        cursor = get_corsor()
        cursor.execute("insert into book(id,name,author) values (null,'%s','%s')" % (name,author))
        return redirect(reverse('front:index'))


def book_detail(request,book_id):
    cursor = get_corsor()
    cursor.execute("select id,name,author from book where id= %s" % book_id)
    book = cursor.fetchone()
    return render(request,'book_detail.html',context={"book": book})


def delete_book(request):
    if request.method == 'POST':
        book_id = request.POST.get('book_id')
        cursor = get_corsor()
        cursor.execute('delete from book where id=%s' % book_id)
        return redirect(reverse('front:index'))
    else:
        raise RuntimeError("删除图书的method错误")

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('delete_book/', views.delete_book, name="delete_book")

]

base,html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书管理系统</title>
    <link rel="stylesheet" href="{% static 'front/base.css' %}">
</head>
<body>
<nav>
    <ul class="nav">
        <li><a href="{% url 'front:index' %}">首页</a></li>
        <li><a href="{% url 'front:add_book' %}">发布图书</a></li>
    </ul>
</nav>

{% block content %}

{% endblock %}

</body>
</html>

index.html

{% extends 'base.html' %}

{% block content %}
    <table>
       <thead>
          <tr>
              <th>序号</th>
              <th>书名</th>
              <th>作者</th>
          </tr>
       </thead>
       <tbody>
       {% 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 %}

       </tbody>
    </table>

{% endblock %}

add_book.html

{% extends 'base.html' %}
{% block content %}
    <form action="" method="post">
      <table>
          <tbody>
             <tr>
                 <td>书名</td>
                 <td><input type="text" name="name"></td>
             </tr>
             <tr>
                 <td>作者</td>
                 <td><input type="text" name="author"></td>
             </tr>
             <tr>
                 <td></td>
                 <td><input type="submit" value="提交"></td>
             </tr>

          </tbody>
      </table>
    </form>
{% endblock %}

book_detail.html

{% extends 'base.html' %}
{% block content %}
    <p>书名:{{ book.1 }}</p>
    <p>作者:{{ book.2 }}</p>
    <form action="{% url 'front:delete_book' %}" method="post">
        <input type="hidden" name="book_id" value="{{ book.0 }}">
        <input type="submit" value="删除按钮">
    </form>
{% endblock %}

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值