新手上路之django项目开发(二)-----mysql数据库配置及其增删改查操作
生活随笔
收集整理的這篇文章主要介紹了
新手上路之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数据库配置及其增删改查操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新手上路之django项目开发(二)--
- 下一篇: Linux下安装并使用MySQL数据库