python新建一个Django项目(连接mysql数据库)

1,python访问mysql

2,python新建一个Django项目,并且创建新页面

3,修改hrsDjango\views.py,增加showDept方法:

from django.shortcuts import render, HttpResponse
import pymysql
from pymysql.cursors import DictCursor

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

def showDept(request):
    # 部门类
    class Dept(object):
        def __init__(self, no, name, addr):
            self.no = no
            self.name = name
            self.addr = addr

    # 1,创建数据库连接对象
    con = pymysql.connect(
        host='localhost', port=3306,
        database='db_python', charset='utf8',
        user='root', password='python3', autocommit=True
    )
    try:
        deptList = []
        with con.cursor(cursor=DictCursor) as cur:
            cur.execute(
                'select deptno as no, deptname as name, deptaddr as addr from tb_dept'
            )
            deptList = cur.fetchall()
    finally:
        con.close()
    print(deptList)
    return render(request, 'testDept.html', {'deptList': deptList})

4,修改hrsDjango\urls.py,添加新的path:

from django.urls import path
from hrsDjango import views

urlpatterns = [
    path('', views.index),
    path('dept/', views.showDept)
]

5,在emp目录下新增一个html文件:testDept.html




    
    部门信息


    

部门信息:


{% for dept in deptList %} {% endfor %}
编号 名称 地址
{ { dept.no }} { { dept.name }} { { dept.addr }}

6,启动server,打开浏览器,在url栏输入:http://127.0.0.1:8000/hrs/dept

python新建一个Django项目(连接mysql数据库)_第1张图片

DB内容:

python新建一个Django项目(连接mysql数据库)_第2张图片

你可能感兴趣的:(从零开始的python3之旅,python,django,mysql,navicat)