Django對資料庫表的操作
阿新 • • 發佈:2018-11-22
一、單表操作
M model.py
import pymysql config = { 'host': '127.0.0.1', 'user': 'fred_li', 'password': '835y1354', 'db': 'assent' } class MyModel(object): def __init__(self): # 連線資料庫 try: self.conn = pymysql.connect(**config) self.curmysql相關操作= self.conn.cursor(cursor=pymysql.cursors.DictCursor) # 結果以列表字典形式返回 except Exception as e: print('connect db error', e) def get_list(self, sql): try: self.cur.execute(sql) res = self.cur.fetchall() return res exceptException as e: print(e) def getone_list(self, sql, args): # 查詢部分資料 try: self.cur.execute(sql, args) res = self.cur.fetchone() return res except Exception as e: print(e) def add(self, sql, args):try: self.cur.execute(sql, args) self.conn.commit() except Exception as e: print('insert to db error', e) def modify(self, sql, args): try: self.cur.execute(sql, args) self.conn.commit() except Exception as e: print('update to db error', e) def close_conn(self): self.cur.close() self.conn.close()
V views.py
from django.shortcuts import render, redirect from app01 import models def accountinfo(request): model = models.MyModel() res = model.get_list('select * from accountinfo where state=0') model.close_conn() return render(request, 'accounts.html', {'accountinfo': res}) def add_account(request): ''' 此功能承擔兩個職責: 1、在賬號列表頁面,當點選新增賬號時,屬於GET操作 2、跳轉到新增賬號頁面,提交資料則屬於POST操作 :param request: :return: ''' model = models.MyModel() if request.method == "GET": res = model.get_list('select * from accountinfo where state=0') model.close_conn() return render(request, 'add_account.html', {'accountinfo': res}) else: name = request.POST.get('accountname') print(name) res = model.add('insert into accountinfo(name) VALUES(%s)', (name)) model.close_conn() return redirect('/accountinfo/') def modify_account(request): model = models.MyModel() if request.method == "GET": accountid = request.GET.get('accountid') res = model.getone_list('select * from accountinfo where state=0 and id=%s', (accountid)) model.close_conn() return render(request, 'modify_account.html', {'accountinfo': res}) else: accountname = request.POST.get('accountname') accountid = request.POST.get('accountid') model.modify('update accountinfo set name=%s where id=%s', (accountname, accountid)) model.close_conn() return redirect('/accountinfo/') def del_account(request): ''' 此處不是物理刪除,只是把賬號的state的值由0(正常),改為1(已刪除) :param request: :return: ''' model=models.MyModel() accountid=request.GET.get('accountid') print(accountid) model.modify('update accountinfo set state=1 where id=%s',(accountid)) model.close_conn() return redirect('/accountinfo/')增刪改查
T 靜態模板檔案
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>賬號查詢</title> <link rel="shortcut icon" href="/static/images/icon.jpg"> <script src="/static/js/jquery.min.js"></script> </head> <body> <h2>賬號列表</h2> <a href="/add_account/">新增賬號</a> <table border="1px"> <tr> <th>賬號id</th> <th>賬號名稱</th> <th>操作</th> </tr> {% for item in accountinfo %} <tr> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td> <a href="/del_account/?accountid={{ item.id }}" onclick="return doConfirm()">刪除</a> <a href="/modify_account/?accountid={{ item.id }}">更新</a> </td> </tr> {% endfor %} </table> </body> <script> function doConfirm() { res=window.confirm('是否要刪除此賬號??') if(res){ return true }else { return false } } </script> </html>查詢頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>新增賬號</title> <link rel="shortcut icon" href="/static/images/icon.jpg"> <script src="/static/js/jquery.min.js"></script> </head> <body> <h2>新增賬號</h2> <!-- action 指定表單向指定url傳送資料--> <form action="/add_account/" method="post"> <input type="text" name="accountname" placeholder="請輸入賬號名稱"> <input type="submit" value="提交"> </form> </body> </html>新增頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>修改伺服器資訊</title> <link rel="shortcut icon" href="/static/images/icon.jpg"> <script src="/static/js/jquery.min.js"></script> </head> <body> <h2>修改伺服器資訊</h2> <form action="/modify_server/" method="post"> <input type="hidden" name="serverid" value="{{ serverinfo.id }}"> <input type="text" name="hostname" value="{{ serverinfo.hostname }}"> <input type="submit" value="提交"> </form> </body> </html>修改頁面
路由層 urls.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^accountinfo/', views.accountinfo), url(r'^add_account/', views.add_account), url(r'^modify_account/', views.modify_account), url(r'^del_account/', views.del_account), ]
# 此處Django版本是1.11.9 url...格式 2.x path....格式