搜尋
首頁資料庫mysql教程Python+Django+SAE系列课程13-MySQL记录的添删改

Python+Django+SAE系列教程13-----MySQL记录的添\删\改 建立了数据库后,我们就来做一个简单的表( person_classroom )的添加、删除、修改的操作。 首先我们建立一个添加的页面的模板 Classroom_Add.html(添加的表单) 并把它放在 Bidding\templates\person

Python+Django+SAE系列教程13-----MySQL记录的添\删\改

建立了数据库后,我们就来做一个简单的表(person_classroom)的添加、删除、修改的操作。

首先我们建立一个添加的页面的模板Classroom_Add.html(添加的表单)并把它放在Bidding\templates\person中:

Classroom_Add.html



    <title>数据库操作简单表的添加</title>


    <h1 id="这里是Classroom的添加页面">这里是Classroom的添加页面</h1>
    {% if error %}
        <p style="color: red;">请输入班级名称和导师姓名</p>
    {% endif %}
   
项目 内容
班级名称:
导师姓名:

Classroom_Add_results.html


    <title>查询用户结果页</title>


    
班级:{{name}}添加成功 !
点击返回
上面的 这个文件时添加后的结果页。

然后建立对应的view,我们修改person/views.py 文件

Views.py

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.db import connection,transaction
from person.models import *

def ClassroonAdd(request):
    if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
        name = request.GET['name']
        tutor = request.GET['tutor']

        cursor=connection.cursor()
        sql='insert into person_classroom (name,tutor) values (\''+name+'\',\''+tutor+'\')'
        cursor.execute(sql)
        transaction.commit_unless_managed()
        cursor.close()
        
        return render_to_response('person/Classroom_Add_results.html',
            {'name': name})
    else:
        return render_to_response('person/Classroom_Add.html', {'error': True})

在修改一下urls.py文件:

from django.conf.urls import patterns, include, url


# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Bidding.views.home', name='home'),
    # url(r'^Bidding/', include('Bidding.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', 'Bidding.views.hello'),
    url(r'^time/$', 'Bidding.views.current_datetime'),
    url(r'^time/plus/(\d{1,2})/$', 'Bidding.views.hours_ahead'),
    url(r'^hello_base/$', 'Bidding.views.hello_base'),
    url(r'^request_test/$', 'Bidding.views.request_test'),
    url(r'^UsersSearch/$', 'Bidding.Users.views.search_form'),
    url(r'^search/$', 'Bidding.Users.views.search'),
    url(r'^ClassRoom/add/$', 'person.views.ClassroonAdd'),
)

这时我们的添加就做好了,访问一下classroom/add这个 页面,就可以看到结果了。




不过上面我们所说的办法是执行一个原始的sql语句,这个方式其实并不是Django推荐的,我们可以直接使用models操作数据库的方法,改造一下ClassroomAdd这个视图:


def ClassroonAdd(request):
    if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
        name = request.GET['name']
        tutor = request.GET['tutor']
        c = ClassRoom(name=name,tutor=tutor)
        c.save()
        
        return render_to_response('person/Classroom_Add_results.html',
            {'name': name})
    else:
        return render_to_response('person/Classroom_Add.html', {'error': True})

这样的方法即简单,有不用我们很多sql的语法,并且最重要的是如果更换数据库类型(sqlserver->oracle),也不会因为受sql语法不一致的影响。

在接下来,我们来做一个列表页,把数据库中的Classroom表的记录以一个表格的形式显示出来。还是从模板先入手,建立一个Classroom_List.html,放入Bidding\templates\person文件夹下:

Classroom_List.html



    <title>数据库操作简单表的添加</title>


    <h1 id="这里是Classroom的管理页面">这里是Classroom的管理页面</h1>
        
{% for myclass in ClassroonList%} {% endfor %}
序号 班级名称 导师姓名
{{ myclass.id }} {{ myclass.name }} {{ myclass.tutor }}

添加视图:

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.db import connection,transaction
from person.models import *

def ClassroonAdd(request):
    if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
        name = request.GET['name']
        tutor = request.GET['tutor']

        cursor=connection.cursor()
        sql='insert into person_classroom (name,tutor) values (\''+name+'\',\''+tutor+'\')'
        cursor.execute(sql)
        transaction.commit_unless_managed()
        cursor.close()
        
        return render_to_response('person/Classroom_Add_results.html',
            {'name': name})
    else:
        return render_to_response('person/Classroom_Add.html', {'error': True})


def ClassroonAdd(request):
    if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
        name = request.GET['name']
        tutor = request.GET['tutor']
        c = ClassRoom(name=name,tutor=tutor)
        c.save()
        
        return render_to_response('person/Classroom_Add_results.html',
            {'name': name})
    else:
        return render_to_response('person/Classroom_Add.html', {'error': True})





def ClassroonList(request):
        cursor=connection.cursor()
        sql='select id,name,tutor from person_classroom'
        ClassroonList=ClassRoom.objects.raw(sql)
        return render_to_response('person/Classroom_List.html',
            {'ClassroonList': ClassroonList})

配置urls.py:

from django.conf.urls import patterns, include, url


# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Bidding.views.home', name='home'),
    # url(r'^Bidding/', include('Bidding.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', 'Bidding.views.hello'),
    url(r'^time/$', 'Bidding.views.current_datetime'),
    url(r'^time/plus/(\d{1,2})/$', 'Bidding.views.hours_ahead'),
    url(r'^hello_base/$', 'Bidding.views.hello_base'),
    url(r'^request_test/$', 'Bidding.views.request_test'),
    url(r'^UsersSearch/$', 'Bidding.Users.views.search_form'),
    url(r'^search/$', 'Bidding.Users.views.search'),
    url(r'^ClassRoom/add/$', 'person.views.ClassroonAdd'),
    url(r'^ClassRoom/list/$', 'person.views.ClassroonList'),
)

如同上述讨论的一样,我们现在的视图执行的是一个原始的sql,现在我们需要用models来修改一下:

def ClassroonList(request):
        cursor=connection.cursor()
        ClassroonList=ClassRoom.objects.all()
        #ClassroonList=ClassRoom.objects.filter(name__icontains='大')
        return render_to_response('person/Classroom_List.html',
            {'ClassroonList': ClassroonList})  

如果需要执行where或者order by等操作可以这样:

 ClassroonList=ClassRoom.objects.filter(name__icontains='').order_by(‘name’)

这里还有很多关于选择的内容以后我们逐渐会介绍到。

做完了列表页,我们在来做一个修改的页面,思路是这样的:在列表页中的每一行的后面添加一列“修改”按钮,点击按钮后跳转到修改页面,首先以此条记录的主键专递到修改页面,在修改页面中要先读取出数据库中的信息,然后点击确定按钮以后执行修改操作。

我们首先来修改这个管理页面的模板:

Classroom_List.html



    <title>数据库操作简单表的添加</title>


    <h1 id="这里是Classroom的管理页面">这里是Classroom的管理页面</h1>
        
{% for myclass in ClassroonList%} {% endfor %}
序号 班级名称 导师姓名 操作
{{ myclass.id }} {{ myclass.name }} {{ myclass.tutor }}

建立一个Classroom_Modify.html模板,把它放在Bidding\templates\person文件夹下

Classroom_Modify.html



    <title>数据库操作简单表的修改</title>


    <h1 id="这里是Classroom-name-的修改页面">这里是Classroom--{{name}}的修改页面</h1>
    {% if error %}
        <p style="color: red;">请输入班级名称和导师姓名</p>
    {% endif %}
   
项目 内容
班级名称:
导师姓名:

Classroom_Modify_results.html


    <title>查询用户结果页</title>


    
  修改前 修改后
班级名称: {{old_name}} {{new_name}}
导师姓名: {{old_tutor}} {{new_tutor}}
修改成功!
点击返回

添加视图:

def ClassroonModify(request,id1):
    cursor=connection.cursor()
    sql='select id,name,tutor from person_classroom where id='+id1
    ClassroonList=ClassRoom.objects.raw(sql)
    old_name = ClassroonList[0].name
    old_tutor = ClassroonList[0].tutor
    if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
        new_name = request.GET['name']
        new_tutor = request.GET['tutor']
        cursor=connection.cursor()
        sql='update person_classroom set name=\''+new_name+'\',tutor=\''+new_tutor+'\' where id=\''+id1+'\''
        cursor.execute(sql)
        transaction.commit_unless_managed()
        cursor.close()
        return render_to_response('person/Classroom_Modify_results.html',
            {'old_name': old_name,'old_tutor':old_tutor,'new_name':new_name,'new_tutor':new_tutor})
    else:
        return render_to_response('person/Classroom_Modify.html', {'error': True,'id':id1,'name':old_name,'tutor':old_tutor})

编辑urls.py,这里面需要注意的是正则的写法,这个之前的章节已经说过了,这里我们可以再复习一遍:

from django.conf.urls import patterns, include, url


# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Bidding.views.home', name='home'),
    # url(r'^Bidding/', include('Bidding.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', 'Bidding.views.hello'),
    url(r'^time/$', 'Bidding.views.current_datetime'),
    url(r'^time/plus/(\d{1,2})/$', 'Bidding.views.hours_ahead'),
    url(r'^hello_base/$', 'Bidding.views.hello_base'),
    url(r'^request_test/$', 'Bidding.views.request_test'),
    url(r'^UsersSearch/$', 'Bidding.Users.views.search_form'),
    url(r'^search/$', 'Bidding.Users.views.search'),
    url(r'^ClassRoom/add/$', 'person.views.ClassroonAdd'),
    url(r'^ClassRoom/list/$', 'person.views.ClassroonList'),
    url(r'^ClassRoom/modify/(\d+)/$', 'person.views.ClassroonModify'),
)

如同添加时候的问题,我们这里面使用的仍然是最原始的sql语句,我们同样可以给他修改成为model的方式:

def ClassroonModify(request,id1):
    cursor=connection.cursor()
    Classroon=ClassRoom.objects.get(id=id1)
    old_name = Classroon.name
    old_tutor = Classroon.tutor
    cursor.close()
    if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
        new_name = request.GET['name']
        new_tutor = request.GET['tutor']
        Classroon.name=new_name
        Classroon.tutor=new_tutor
        Classroon.save()
        return render_to_response('person/Classroom_Modify_results.html',
            {'old_name': old_name,'old_tutor':old_tutor,'new_name':new_name,'new_tutor':new_tutor})
    else:
        return render_to_response('person/Classroom_Modify.html', {'error': True,'id':id1,'name':old_name,'tutor':old_tutor})

这样看起来是不是简便多了?我们打开 页面看看效果吧 :




接下来我们来做删除的功能,首先修改列表页的模板,加入一列删除按钮:



    <title>数据库操作简单表的添加</title>


    <h1 id="这里是Classroom的管理页面">这里是Classroom的管理页面</h1>
        
{% for myclass in ClassroonList%} {% endfor %}
序号 班级名称 导师姓名 操作
{{ myclass.id }} {{ myclass.name }} {{ myclass.tutor }}

Classroom_Delete_results.html:


    <title>查询用户结果页</title>


    
班级:{{name}}删除成功 !
点击返回

修改视图:

def ClassroonDelete(request,id1):
    cursor=connection.cursor()
    Classroon=ClassRoom.objects.get(id=id1)
    old_name = Classroon.name
    Classroon.delete()
    ClassroonList=ClassRoom.objects.all()
    cursor.close()
  return render_to_response('person/Classroom_Delete_results.html',{'name':old_name})

配置urls.py:

from django.conf.urls import patterns, include, url


# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Bidding.views.home', name='home'),
    # url(r'^Bidding/', include('Bidding.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', 'Bidding.views.hello'),
    url(r'^time/$', 'Bidding.views.current_datetime'),
    url(r'^time/plus/(\d{1,2})/$', 'Bidding.views.hours_ahead'),
    url(r'^hello_base/$', 'Bidding.views.hello_base'),
    url(r'^request_test/$', 'Bidding.views.request_test'),
    url(r'^UsersSearch/$', 'Bidding.Users.views.search_form'),
    url(r'^search/$', 'Bidding.Users.views.search'),
    url(r'^ClassRoom/add/$', 'person.views.ClassroonAdd'),
    url(r'^ClassRoom/list/$', 'person.views.ClassroonList'),
    url(r'^ClassRoom/modify/(\d+)/$', 'person.views.ClassroonModify'),
    url(r'^ClassRoom/delete/(\d+)/$', 'person.views.ClassroonDelete'),
)


到此,我们就做好了一个简单的表的添加、删除、修改的操作。


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
解釋InnoDB緩衝池及其對性能的重要性。解釋InnoDB緩衝池及其對性能的重要性。Apr 19, 2025 am 12:24 AM

InnoDBBufferPool通過緩存數據和索引頁來減少磁盤I/O,提升數據庫性能。其工作原理包括:1.數據讀取:從BufferPool中讀取數據;2.數據寫入:修改數據後寫入BufferPool並定期刷新到磁盤;3.緩存管理:使用LRU算法管理緩存頁;4.預讀機制:提前加載相鄰數據頁。通過調整BufferPool大小和使用多個實例,可以優化數據庫性能。

MySQL與其他編程語言:一種比較MySQL與其他編程語言:一種比較Apr 19, 2025 am 12:22 AM

MySQL与其他编程语言相比,主要用于存储和管理数据,而其他语言如Python、Java、C 则用于逻辑处理和应用开发。MySQL以其高性能、可扩展性和跨平台支持著称,适合数据管理需求,而其他语言在各自领域如数据分析、企业应用和系统编程中各有优势。

學習MySQL:新用戶的分步指南學習MySQL:新用戶的分步指南Apr 19, 2025 am 12:19 AM

MySQL值得學習,因為它是強大的開源數據庫管理系統,適用於數據存儲、管理和分析。 1)MySQL是關係型數據庫,使用SQL操作數據,適合結構化數據管理。 2)SQL語言是與MySQL交互的關鍵,支持CRUD操作。 3)MySQL的工作原理包括客戶端/服務器架構、存儲引擎和查詢優化器。 4)基本用法包括創建數據庫和表,高級用法涉及使用JOIN連接表。 5)常見錯誤包括語法錯誤和權限問題,調試技巧包括檢查語法和使用EXPLAIN命令。 6)性能優化涉及使用索引、優化SQL語句和定期維護數據庫。

MySQL:初學者的基本技能MySQL:初學者的基本技能Apr 18, 2025 am 12:24 AM

MySQL適合初學者學習數據庫技能。 1.安裝MySQL服務器和客戶端工具。 2.理解基本SQL查詢,如SELECT。 3.掌握數據操作:創建表、插入、更新、刪除數據。 4.學習高級技巧:子查詢和窗口函數。 5.調試和優化:檢查語法、使用索引、避免SELECT*,並使用LIMIT。

MySQL:結構化數據和關係數據庫MySQL:結構化數據和關係數據庫Apr 18, 2025 am 12:22 AM

MySQL通過表結構和SQL查詢高效管理結構化數據,並通過外鍵實現表間關係。 1.創建表時定義數據格式和類型。 2.使用外鍵建立表間關係。 3.通過索引和查詢優化提高性能。 4.定期備份和監控數據庫確保數據安全和性能優化。

MySQL:解釋的關鍵功能和功能MySQL:解釋的關鍵功能和功能Apr 18, 2025 am 12:17 AM

MySQL是一個開源的關係型數據庫管理系統,廣泛應用於Web開發。它的關鍵特性包括:1.支持多種存儲引擎,如InnoDB和MyISAM,適用於不同場景;2.提供主從復制功能,利於負載均衡和數據備份;3.通過查詢優化和索引使用提高查詢效率。

SQL的目的:與MySQL數據庫進行交互SQL的目的:與MySQL數據庫進行交互Apr 18, 2025 am 12:12 AM

SQL用於與MySQL數據庫交互,實現數據的增、刪、改、查及數據庫設計。 1)SQL通過SELECT、INSERT、UPDATE、DELETE語句進行數據操作;2)使用CREATE、ALTER、DROP語句進行數據庫設計和管理;3)複雜查詢和數據分析通過SQL實現,提升業務決策效率。

初學者的MySQL:開始數據庫管理初學者的MySQL:開始數據庫管理Apr 18, 2025 am 12:10 AM

MySQL的基本操作包括創建數據庫、表格,及使用SQL進行數據的CRUD操作。 1.創建數據庫:CREATEDATABASEmy_first_db;2.創建表格:CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY,titleVARCHAR(100)NOTNULL,authorVARCHAR(100)NOTNULL,published_yearINT);3.插入數據:INSERTINTObooks(title,author,published_year)VA

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器