python在前端页面使用 MySQLdb 连接数据

 更新时间:2022年03月24日 14:08:06   作者:Keep_Trying_Go  
这篇文章主要介绍了MySQLdb 连接数据的使用,文章主要介绍的相关内容又插入数据,删除数据,更新数据,搜索数据,需要的小伙伴可以参考一下

1.文件结构

在这里插入图片描述

MySQLdb和pymysql的使用差不多阅读的小伙伴可以自己尝试实现

2.实验效果

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

3.主文件:main.py

import MySQLdb
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired,EqualTo,Length
from wtforms import StringField,SubmitField,PasswordField,TelField
from flask import Flask,render_template,redirect,url_for,abort,request,jsonify

app=Flask(__name__)
app.secret_key='stu'

#连接数据mysql
conn=MySQLdb.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    password='root',
    db='main'
)
cur=conn.cursor()

#增加用户表单
class StuForm(FlaskForm):
    name=StringField(label='用户名: ',validators=[DataRequired()])
    password=PasswordField(label='密码: ',validators=[DataRequired(),Length(min=3,max=8)])
    submit=SubmitField(label='提交')

#搜索用户表单
class SStuForm(FlaskForm):
    name = StringField(label='用户名: ', validators=[DataRequired()])
    submit=SubmitField(label='提交')

#更新用户表单
class UStuForm(FlaskForm):
    name = StringField(label='用户名: ', validators=[DataRequired()])
    password = PasswordField(label='密码: ', validators=[DataRequired(), Length(min=3, max=8)])
    submit = SubmitField(label='提交')

#删除用户表单
class DStuForm(FlaskForm):
    name = StringField(label='用户名: ', validators=[DataRequired()])
    submit = SubmitField(label='提交')

def CreateTab():
    sql="create table student(name varchar(20),password varchar(30))"
    cur.execute(sql)
    conn.commit()
    cur.close()

@app.route('/add',methods=['POST','GET'])
def add():
    stuform=StuForm()
    if request.method=='POST':
        if stuform.validate_on_submit():
            name=stuform.name.data
            password=stuform.password.data
            print('name: {}'.format(name))
            print('password: {}'.format(password))
            sql=f"insert into student(name,password) values('{name}','{password}')"
            cur.execute(sql)
            conn.commit()
            return jsonify('Add Successed!')
    return render_template('add.html',stuform=stuform)

@app.route('/search',methods=['POST','GET'])
def search():
    sstuform=SStuForm()
    if request.method=='POST':
        if sstuform.validate_on_submit():
            name=sstuform.name.data
            sql=f"select count(name) from student where name='{name}'"
            cur.execute(sql)
            conn.commit()
            count=cur.fetchone()[0]
            if count<=0:
                return jsonify('The User is not exist!')
            else:
                sql=f"select name,password from student where name='{name}'"
                cur.execute(sql)
                conn.commit()
                result=cur.fetchall()
                return jsonify(result)
    return render_template('search.html',sstuform=sstuform)

@app.route('/update',methods=['POST','GET'])
def update():
    ustuform=UStuForm()
    if request.method=='POST':
        if ustuform.validate_on_submit():
            name = ustuform.name.data
            password=ustuform.password.data
            sql = f"select count(name) from student where name='{name}'"
            cur.execute(sql)
            conn.commit()
            count = cur.fetchone()[0]
            if count <= 0:
                return jsonify('The User is not exist!')
            else:
                sql = f"update student set name='{name}',password='{password}'  where name='{name}'"
                cur.execute(sql)
                conn.commit()
                return jsonify('Update Successed!')
    return render_template('update.html',ustuform=ustuform)
@app.route('/delete',methods=['POST','GET'])
def delete():
    dstuform=DStuForm()
    if request.method=='POST':
        if dstuform.validate_on_submit():
            name=dstuform.name.data
            sql = f"select count(name) from student where name='{name}'"
            cur.execute(sql)
            conn.commit()
            count = cur.fetchone()[0]
            if count <= 0:
                return jsonify('The User is not exist!')
            else:
                sql=f"delete from student where name='{name}'"
                cur.execute(sql)
                conn.commit()
                return jsonify('Delete Successed!')

    return render_template('delete.html',dstuform=dstuform)

@app.route('/function',methods=['POST','GET'])
def function():
    if request.method=='POST':
        submit1 = request.form.get('submit1')
        submit2 = request.form.get('submit2')
        submit3 = request.form.get('submit3')
        submit4 = request.form.get('submit4')
        print('submit1: {}'.format(submit1))
        print('submit2: {}'.format(submit2))
        print('submit3: {}'.format(submit3))
        print('submit4: {}'.format(submit4))
        if submit1 is not None:
            return redirect(url_for('add'))
        if submit2 is not None:
            return redirect(url_for('search'))
        if submit3 is not None:
            return redirect(url_for('update'))
        if submit4 is not None:
            return redirect(url_for('delete'))
    return render_template('base.html')
if __name__ == '__main__':
    print('Pycharm')
    # CreateTab()
    app.run(debug=True)

4.base.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .h1{
            position:relative;
            margin:auto;
            width:500px;
            height:50px;
            margin-top:100px;
            margin-left:650px;
        }
        .form {
            position:relative;
            width:500px;
            height:50px;
            margin:auto;
            margin-top:50px;
            border:2px solid #000000;
            color:#000000;
            font-size:20px;
            font-weight:400;
        }
        .form1{
            position:absolute;
            margin-top:10px;
            margin-left:80px;
        }
        .form2{
            position:absolute;
            margin-top:10px;
            margin-left:180px;
        }
        .form3{
            position:absolute;
            margin-top:10px;
            margin-left:280px;
        }
        .form4{
            position:absolute;
            margin-top:10px;
            margin-left:380px;
        }
    </style>
</head>
<body>
    <div class="h1">
        <h1>功能选择</h1>
    </div>
    <div class="form">
        <form class="form1" action="http://127.0.0.1:5000/add" method="POST">
            <input type="submit" name="submit1" value="添加">
        </form>
        <form class="form2" action="http://127.0.0.1:5000/search" method="POST">
            <input type="submit" name="submit2" value="搜索">
        </form>
        <form class="form3" action="http://127.0.0.1:5000/update" method="POST">
            <input type="submit" name="submit3" value="更新">
        </form>
        <form class="form4" action="http://127.0.0.1:5000/delete" method="POST">
            <input type="submit" name="submit4" value="删除">
        </form>
    </div>
</body>
</html>

5.update.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Insert</title>
    <style>
        div{
          width:255px;
          height:100px;
          margin:auto;
          margin-top:200px;
          border:2px solid #000000;
          font-size:20px;
          font-weight:400px;
          background:#FFFFFF;
        }
        .submit{
            margin-top:10px;
            margin-left:100px;
        }
    </style>
</head>
<body>
  <div>
      <form action="" method="POST">
          {{ustuform.csrf_token()}}
          {{ustuform.name.label}}{{ustuform.name}}<br>
          {{ustuform.password.label}}{{ustuform.password}}<br>
          <input class="submit" type="submit" name="submit" value="更新">
      </form>
  </div>
</body>
</html>

6.delete.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Insert</title>
    <style>
        div{
          width:255px;
          height:100px;
          margin:auto;
          margin-top:200px;
          border:2px solid #000000;
          font-size:20px;
          font-weight:400px;
          background:#FFFFFF;
        }
        .submit{
            margin-top:10px;
            margin-left:100px;
        }
    </style>
</head>
<body>
  <div>
      <form action="" method="POST">
          {{dstuform.csrf_token()}}
          {{dstuform.name.label}}{{dstuform.name}}<br>
          <input class="submit" type="submit" name="submit" value="删除">
      </form>
  </div>
</body>
</html>

7.search.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Insert</title>
    <style>
        div{
          width:255px;
          height:100px;
          margin:auto;
          margin-top:200px;
          border:2px solid #000000;
          font-size:20px;
          font-weight:400px;
          background:#FFFFFF;
        }
        .submit{
            margin-top:10px;
            margin-left:100px;
        }
    </style>
</head>
<body>
  <div>
      <form action="" method="POST">
          {{sstuform.csrf_token()}}
          {{sstuform.name.label}}{{sstuform.name}}<br>
          <input class="submit" type="submit" name="submit" value="搜索">
      </form>
  </div>
</body>
</html>

到此这篇关于MySQ Ldb 连接数据的使用的文章就介绍到这了,更多相关MySQLdb连接数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python列表推导式的原理及使用方法

    python列表推导式的原理及使用方法

    这篇文章主要介绍了python列表推导式的原理及使用方法,列表推导式即list comprehension,有时也被翻译为列表解析式,是一种创建列表的简洁语法,更多详细内容需要的小伙伴可以参考一下下面文章相关资料
    2022-03-03
  • Python tkinter三种布局实例详解

    Python tkinter三种布局实例详解

    这篇文章主要介绍了Python tkinter三种布局实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • python读取.data文件的实现

    python读取.data文件的实现

    本文主要介绍了python读取.data文件的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-02-02
  • Django获取model中的字段名和字段的verbose_name方式

    Django获取model中的字段名和字段的verbose_name方式

    这篇文章主要介绍了Django获取model中的字段名和字段的verbose_name方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • Python GUI布局尺寸适配方法

    Python GUI布局尺寸适配方法

    今天小编就为大家分享一篇Python GUI布局尺寸适配方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • Python中optionParser模块的使用方法实例教程

    Python中optionParser模块的使用方法实例教程

    这篇文章主要介绍了Python中optionParser模块的使用方法,功能非常强大,需要的朋友可以参考下
    2014-08-08
  • python基础_文件操作实现全文或单行替换的方法

    python基础_文件操作实现全文或单行替换的方法

    下面小编就为大家带来一篇python基础_文件操作实现全文或单行替换的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • Python使用QQ邮箱发送邮件报错smtplib.SMTPAuthenticationError

    Python使用QQ邮箱发送邮件报错smtplib.SMTPAuthenticationError

    这篇文章主要介绍了Python使用QQ邮箱发送邮件报错smtplib.SMTPAuthenticationError,简单介绍了python 发送邮件的步骤,需要的朋友可以参考下
    2019-12-12
  • 数组保存为txt, npy, csv 文件, 数组遍历enumerate的方法

    数组保存为txt, npy, csv 文件, 数组遍历enumerate的方法

    今天小编就为大家分享一篇数组保存为txt, npy, csv 文件, 数组遍历enumerate的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • 利用Python实现智能合约的示例详解

    利用Python实现智能合约的示例详解

    智能合约是一种由计算机程序编写的自动化合约,它可以在没有第三方干预的情况下执行交易和契约条款。这篇文章主要介绍了如何利用Python实现智能合约,需要的可以参考一下
    2023-04-04

最新评论