python的flask框架查詢數據庫,將數據庫的某幾列顯示到web頁面


首先數據庫長這樣

 

我們想將name和age列顯示到web頁面

上代碼sqlshowweb.py

from flask import Flask
from flask import render_template
import pymysql

app = Flask(__name__)


@app.route('/')
def index():
    conn = pymysql.connect(host='39.106.168.84', user='xxxx', password='xxxxxxxx', port=3306,
                        db='xxxx')
    cur = conn.cursor()
    sql = "SELECT `name`, `age` FROM `student` WHERE 1"
    cur.execute(sql)
    u = cur.fetchall()
    conn.close()
    return render_template('index.html',u=u)
if __name__ == '__main__':
    app.debug = True
    app.run(port=8003)

index.html

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

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

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

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

</body>
</html>

運行結果

 

 代碼在git上 https://github.com/qingnvsue/flask 的sql文件夾


免責聲明!

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



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