新手上路之django项目开发(二)-----mysql数据库配置及其增删改查操作

1,数据库配置(settings.py文件配置)

我这里用的是本地数据库。

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'information',
    'USER': 'root',
    'PASSWORD': '',
    'HOST': '127.0.0.1',
    'PORT': '3306',
  }
}

NAME是数据库名称,USER是MYSQL账户,PASSWORD是密码,HOST是主机,PORT是端口。

2,数据库查询数据

在views.py文件中:

from django.db import connection
def infor(request):
    with connection.cursor() as cur:
        cur.execute('select * from infor;')
        res = cur.fetchall()
        # res = cur.fetchone()
    return HttpResponse('hello!!!')

cur.fetchall()查询到全部数据之后就可以用python操作数据啦。
res = cur.fetchone() 查询某一条数据

3,数据库插入数据
def infor_ajax(request):
    if request.method == "POST":
        # 获取前端提交的数据
        username = request.POST.get("name", 0)
        age = request.POST.get("age", 0)
        # 添加到数据库
        with connection.cursor() as cur:
            cur.execute('insert into infor values (%s, %s)', (username, age))
    return render(request, 'index.html')
4,数据库删除数据
def deleteinfor(request):
	if request.method == "POST":
        # 获取前端提交的数据
        name = request.POST.get("name", 0)
        age = request.POST.get("age", 0)
    	with connection.cursor() as cur:
       		cur.execute("delete * from infor where username=%s",(name))
       		# res = cur.fetchall()
    return HttpResponse('success!!!')
5,数据库修改更新数据
def updateinfor(request):
	if request.method == "POST":
        # 获取前端提交的数据
        name = request.POST.get("name", 0)
        age = request.POST.get("age", 0)
    	with connection.cursor() as cur:
       		cur.execute("update infor set username=%s",(name))
       		# res = cur.fetchall()
    return HttpResponse('success!!!')
6,views.py中return的方式
6.1,return render()
return render(request, 'index.html')
return render(request, 'index.html', {'msg': '提交成功!'})

在html页面中调用则是:{{ msg }}

6.2,return HttpResponse()
return HttpResponse('hello!!!')
6.3,return HttpResponseRedirect()
return HttpResponseRedirect('/index/')
return HttpResponseRedirect('/index/', {'msg': '提交成功!'})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值