python的flask框架下從web輸入信息,將其存入數據庫,然后調用數據庫,將其顯示到web頁面


數據庫如圖

 

 我們在web輸入一行信息,如圖

 

 插入數據庫,如圖

 

 可以看到,這行信息已經插入了,然后我們將新插入的這行信息顯示到web頁面

 

 整個流程就是這樣,代碼如下:

sqlinputweb.py

from flask import Flask, render_template, request
import pymysql
app = Flask(__name__)

class DataStore():
    a = None
data = DataStore()

@app.route('/', methods=['GET'])
def home():
    return render_template('index2.html')


@app.route('/', methods=['POST'])
def add():
    id = request.form['id']
    data.a = id
    name = request.form['name']
    age = request.form['age']
    sex= request.form['sex']
    try:
        id= float(id)
        age = float(age)
        conn = pymysql.connect(host='39.106.168.84', user='xxxxxx', password='xxxxxxx', port=3306,
                               db='xxxxx')
        cur = conn.cursor()  # 生成游標對象
        sql = "INSERT INTO `student`(`id`, `name`, `age`, `sex`) VALUES (%s,%s,%s,%s)",(id, name, age, sex)
        try:
            # 執行sql語句
            cur.execute(*sql)
            # 提交到數據庫執行
            conn.commit()
        except:
            # 如果發生錯誤則回滾
            conn.rollback()

        sql = "SELECT * FROM `student` WHERE `id` = %s" % data.a
        cur.execute(sql)
        u = cur.fetchall()
        conn.close()
        return render_template('index3.html', u=u)
        conn.close()
    except:
        return render_template('index2.html', message='inputs false!!!', var1=id, var2=name, var3=age, var4=sex)


if __name__ == '__main__':
    app.run(port=8002)

index2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>sql測試</title>
</head>
<body>
<div align="center" style="margin-top: 40px;">
    <form name="form1"     method="POST">
        id =<input type="text" placeholder="id" name="id" value="{{ var1  }}">
        name=<input type="text" placeholder="name" name="name" value="{{ var2  }}">
        age=<input type="text" placeholder="age" name="age" value="{{ var3  }}">
        sex=<input type="text" placeholder="sex" name="sex" value="{{ var4  }}">
        <input type="submit" value="提交" οnclick="">
    </form>

</div>
{% if message %}
    <p style="color:red">{{ message }}</p>
    {% endif %}
</body>

index3.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <table class="table table-bordered">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>age</th>
        <th>sex</th>

    </tr>
        {% for i in u %}
            <tr>
                <td>{{ i[0] }}</td>
                <td>{{ i[1] }}</td>
                <td>{{ i[2] }}</td>
                <td>{{ i[3] }}</td>

            </tr>
        {% endfor %}
    </table>

</body>
</html>

代碼詳見git的https://github.com/qingnvsue/flask 中的sql文件夾


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM