为了实现Web版的增删改查(CRUD),你需要使用Python的Django框架和MySQL数据库。以下是实现CRUD操作的基本步骤和示例代码:
- 安装Django和MySQL的Python库:
pip install django
pip install mysqlclient
- 创建Django项目和应用:
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
- 配置
settings.py
以使用MySQL数据库:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '3306',
}
}
- 定义模型(
models.py
):
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
- 迁移数据库和创建超级用户:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
- 在视图(
views.py
)中创建CRUD操作:
from django.shortcuts import render
from .models import MyModel
from django.http import HttpResponseRedirect
def create(request):
if request.method == 'POST':
name = request.POST['name']
description = request.POST['description']
MyModel.objects.create(name=name, description=description)
return HttpResponseRedirect('/')
return render(request, 'create.html')
def read(request):
items = MyModel.objects.all()
return render(request, 'read.html', {'items': items})
def update(request, pk):
item = MyModel.objects.get(pk=pk)
if request.method == 'POST':
item.name = request.POST['name']
item.description = request.POST['description']
item.save()
return HttpResponseRedirect('/')
return render(request, 'update.html', {'item': item})
def delete(request, pk):
item = MyModel.objects.get(pk=pk)
if request.method == 'POST':
item.delete()
return HttpResponseRedirect('/')
return render(request, 'delete.html', {'item': item})
- 创建对应的HTML模板:
- create.html
- read.html (使用循环显示所有记录)
- update.html
- delete.html
- 配置URLs(
urls.py
):
from django.urls import path
from .views import create, read, update, delete
urlpatterns = [
path('create/', create, name='create'),
path('', read, name='read'),
path('update/<int:pk>/', update, name='update'),
path('delete/<int:pk>/', delete, name='delete'),
]
- 运行Django开发服务器:
pyth