定制设计Python+Flask对MySQL数据库进行增删查改并在页面展示数据

Python+对MySQL定制设计数据库进行增删查改并定制设计在页面展示数据

一、python连接mysql数据库

1. 安装pymysql驱动

PyMySQL 是在 Python3.x 定制设计版本中用于连接 MySQL 定制设计服务器的一个库,Python2中则使用mysqldb。

pip install pymysql
  • 1

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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

二、Flask+Python对数据库数据的操作

Flask相关知识点:

1. 查询数据

这一部分的操作是分了两个py文件来写,一个是专门写对数据库操作的,一个是专门flask操作

  • sql_lianjie.py 定义一个类,对数据库进行操作
import pymysqlclass 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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • sql_flask.py 是使用flask路由对数据进行展示
    千万不要忘记导入对数据库操作的类
from flask import Flask,render_template,requestimport pymysql#导入数据库操作类from sql_lianjie import Mysqlapp = 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'))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 结果:打开网页: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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • result_insert.html
<body>   你已成功插入数据!点击查看数据可查看更新后的数据!   <br>   插入的name为:{{results['name']}}<br>   插入的age为:{{results['age']}}<br>   <br>   <a href="/info"><button>查看数据</button></a></body>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 结果:在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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 结果参考插入数据效果

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 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • result_dalete.html
<body>   你已成功删除id:{{id}}的数据!   <br>   点击查看数据看查询更新后的数据!   <br>   <br>   <a href="/info"><button>查看数据</button></a></body>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  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);
网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发