search
HomeDatabaseMysql TutorialPython+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'),
)


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


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)