Python flask框架實現查詢資料庫並顯示資料
阿新 • • 發佈:2020-06-05
首先資料庫長這樣
我們想將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='flask_topvj_net',password='xxxxxxxx',port=3306,db='flask_topvj_net') 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資料夾
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。