日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

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

發布時間:2023/12/2 数据库 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 新手上路之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': '提交成功!'})

總結

以上是生活随笔為你收集整理的新手上路之django项目开发(二)-----mysql数据库配置及其增删改查操作的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。