Tangwx

Tangwx

博客网站

Python+flask對MySQL資料庫進行增刪改查

Python+Flask 對 MySQL 資料庫進行增刪查改並在頁面展示數據#

來源

一、python 連接 mysql 資料庫#

1. 安裝 pymysql 驅動#

PyMySQL 是在 Python3.x 版本中用於連接 MySQL 伺服器的一個庫,Python2 中則使用 mysqldb。

pip3 install pymysql

2. 資料庫表測試數據#

可以使用 navicat 也可以使用命令行,創建一張表
在這裡插入圖片描述

3. 連接資料庫#

import pymysql
#打開資料庫連接
db = pymysql.connect(host="localhost",user="root",password="123456",database="test")
#使用cursor()方法獲取操作游標 
cursor = db.cursor()
#sql語句
sql = "select * from info"
try:
    #執行sql語句
    cursor.execute(sql)
    #查詢中的一個操作,獲取所有記錄
    result = cursor.fetchall()
    #打印表數據
    for row in result:
        id = row[0]
        name = row[1]
        age = row[2]
        print(id,name,age)
except:
    print("Error!")
#關閉資料庫
db.close()

在這裡插入圖片描述

二、Flask+Python 對資料庫數據的操作#

Flask 相關知識點:Flask 框架學習筆記

1. 查詢數據#

這一部分的操作是分了兩個 py 文件來寫,一個是專門寫對資料庫操作的,一個是專門 flask 操作

  • sql_lianjie.py 定義一個類,對資料庫進行操作
import pymysql
class Mysql(object):
    def __init__(self):
        try:
            self.db = pymysql.connect(host="localhost",user="root",password="123456",database="test")
            #游標對象
            self.cursor = self.db.cursor()
            print("連接成功!")
        except:
            print("連接失敗!")
 	#查詢數據函數
    def getdata(self):
        sql = "select * from info"
        #執行sql語句
        self.cursor.execute(sql)
        #獲取所有的記錄
        results = self.cursor.fetchall()
        return results
    #關閉
    def __del__(self):
        self.db.close()
  • sql_flask.py 是使用 flask 路由對數據進行展示
    千萬不要忘記導入對資料庫操作的類
from flask import Flask,render_template,request
import pymysql
#導入資料庫操作類
from sql_lianjie import Mysql
app = Flask(__name__)

@app.route("/info",methods=['GET','POST'])
def info():
    #調用
    db = Mysql()
    results = db.getdata()
    return render_template("sql_select.html",results=results)
    
if __name__ == "__main__":
    app.run(app.run(debug=True,port=5000,host='127.0.0.1'))
  • sql_select.html 這個頁面是把數據展示在網頁上 (只展示部分代碼)
<body>
<div>
    <h4>查詢數據</h4>
    <table border="1" width="30%" weight="30%">
        <thead>
        <tr>
            <th>id</th>
            <th>name</th>
            <th>age</th>
        </tr>
        </thead>
        <tbody>
            {% for result in results %}
                <tr>
                    <td>{{ result[0]}}</td>
                    <td>{{ result[1]}}</td>
                    <td>{{ result[2]}}</td>
                    <td><a href="/delete?id={{ result[0] }}"><button>刪除</button></a></td>
                    <td><a href="/submit_insert"><button>插入</button></a></td>
                    <td><a href="/submit_update"><button>修改</button></a></td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
  • 結果:打開網頁:http://localhost:5000/info
    在這裡插入圖片描述

2. 插入數據#

  • sql_lianjie.py
def insertdata(self,results):
        sql = "insert into info(name,age)values('%s','%s')" % (results['name'],results['age'])
        sql1 = "ALTER TABLE info DROP id"
        sql2 = "ALTER TABLE info ADD id int NOT NULL FIRST"
        sql3 = "ALTER TABLE info MODIFY COLUMN id int NOT NULL AUTO_INCREMENT,ADD PRIMARY KEY(id)"
        try:
            self.cursor.execute(sql)
            self.cursor.execute(sql1)
            self.cursor.execute(sql2)
            self.cursor.execute(sql3)
            self.db.commit()
        except:
            # 如果發生錯誤就回滾,建議使用這樣發生錯誤就不會對表數據有影響
            self.db.rollback()
        return
  • sql_flask.py
@app.route("/submit_insert")
def submit_insert():
    return render_template("sql_insert.html")
    
@app.route("/insert",methods=['GET','POST'])
def insert():
    if request.method == "POST":
        results = request.form
        db = Mysql()
        db.insertdata(results)
        return render_template("result_insert.html",results=results)
  • sql_insert.html
<div>
    <h4>在該頁面可以插入數據</h4>
    <!--通過改變form標籤中method屬性來改變數據請求的方式-->
    <form action="http://localhost:5000/insert" method="POST">
        name:<input type="text" name="name" autocomplete="off"><br/><br/>
        age:<input type="text" name="age" autocomplete="off"><br/><br/>
        <button onclick="myFunction()">提交</button>       <a href="/info"><button>查看數據</button></a>
        <p id="demo"></p>
    </form> 
    <script>
        function myFunction(){
            var txt;
            confirm("Successfully inserted data!");
            txt = "你已成功插入數據!點擊查看數據可查看更新後的數據";
            document.getElementById("demo").innerHTML = txt;
        }
    </script>
</div>
  • result_insert.html
<body>
   你已成功插入數據!點擊查看數據可查看更新後的數據!
   <br>
   插入的name為:{{results['name']}}<br>
   插入的age為:{{results['age']}}<br>
   <br>
   <a href="/info"><button>查看數據</button></a>
</body>
  • 結果:在info這個頁面點擊插入按鈕就可以跳轉到插入數據頁面,在這個頁面輸入要插入的數據 (id 不需要輸入,因為設置了自增)
    在這裡插入圖片描述
    點擊提交按鈕,就可以看到數據已經成功插入
    在這裡插入圖片描述
    再點擊查看數據按鈕,就可以成功看到插入後的數據
    在這裡插入圖片描述

3. 修改數據#

  • sql_lianjie.py
def updatedata(self,results):
        sql = "update info set name='%s',age='%s' where id='%s'" % (results['name'],results['age'],results['id'])
        sql1 = "ALTER TABLE info DROP id"
        sql2 = "ALTER TABLE info ADD id int NOT NULL FIRST"
        sql3 = "ALTER TABLE info MODIFY COLUMN id int NOT NULL AUTO_INCREMENT,ADD PRIMARY KEY(id)"
        try:
            self.cursor.execute(sql)
            self.cursor.execute(sql1)
            self.cursor.execute(sql2)
            self.cursor.execute(sql3)
            self.db.commit()
        except:
            # 如果發生錯誤就回滾,建議使用這樣發生錯誤就不會對表數據有影響
            self.db.rollback()
        return
  • sql_flask.py
@app.route("/submit_update")
def submit_update():
    return render_template("sql_update.html")
    
@app.route("/update",methods=['GET','POST'])
def update():
    if request.method == "POST":
        results = request.form
        db = Mysql()
        db.updatedata(results)
        return render_template("result_update.html",results=results)
  • sql_update.html
<div>
    <h4>在該頁面修改你的數據</h4>
    <!--通過改變form標籤中method屬性來改變數據請求的方式-->
    <form action="http://localhost:5000/update" method="POST">
        請輸入你需要修改的id:<input type="text" name="id" autocomplete="off"><br/>
        請輸入修改的name:<input type="text" name="name" autocomplete="off"><br/>
        請輸入修改的age:<input type="text" name="age" autocomplete="off"><br/>
        <input type="submit" value="Submit">
    </form> 
    <a href="/info"><button>查看數據</button></a>
</div>
  • result_update.html
<body>
   你已成功修改數據!
   <br>
   點擊查看數據可查看更新後的數據!
   <br>
   修改的id為:{{results['id']}}<br>
   修改的name為:{{results['name']}}<br>
   修改的age為:{{results['age']}}<br>
   <br>
   <a href="/info"><button>查看數據</button></a>
</body>
  • 結果參考插入數據效果

4. 刪除數據#

  • sql_lianjie.py
def deletedata(self,id):
        sql = "delete from info where id=" + str(id)
        sql1 = "ALTER TABLE info DROP id"
        sql2 = "ALTER TABLE info ADD id int NOT NULL FIRST"
        sql3 = "ALTER TABLE info MODIFY COLUMN id int NOT NULL AUTO_INCREMENT,ADD PRIMARY KEY(id)"
        try:
            # 執行sql語句
            self.cursor.execute(sql)
            self.cursor.execute(sql1)
            self.cursor.execute(sql2)
            self.cursor.execute(sql3)
            # 提交數據
            self.db.commit()
        except:
            # 如果發生錯誤就回滾,建議使用這樣發生錯誤就不會對表數據有影響
            self.db.rollback()
        return 
  • sql_flask.py
@app.route("/delete")
def delete():
    id = request.args.get("id")
    db = Mysql()
    db.deletedata(id)
    return render_template("result_delete.html",id=id)
  • result_delete.html
<body>
   你已成功刪除id為:{{id}}的數據!
   <br>
   點擊查看數據看查詢更新後的數據!
   <br>
   <br>
   <a href="/info"><button>查看數據</button></a>
</body>
  1. 在更新、修改、刪除操作裡面的 sql1-3 的作用是當我表中數據發生改變時,id 會自動更新排序,即如果不加這三行,當我刪除中間的數據,中間那些數據的 id 無法自動重新排序
    代碼:
    刪除原有主鍵:ALTER TABLE news DROP NewsID;
    添加新的主鍵:ALTER TABLE news ADD NewsID int NOT NULL FIRST;
    設置新的主鍵:ALTER TABLE news MODIFY COLUMN NewsID int NOT NULL AUTO_INCREMENT,ADD PRIMARY KEY(NewsID);
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。