我們使用pycharm編輯器,創建項目的時候記得直接創建flask項目,這樣就會有現成的flask框架啦:
項目創建好就是這樣的啦:
static是用於存放靜態文件的,比如圖片、css文件、js文件等;templates是用於存放html文件的;app.py就是用於存放路由器的了
要展示數據庫的數據,主要思路就是連接數據庫,獲取需要的數據,再傳給html頁面接可以了。
所以首先要連接數據庫:
conn = pymysql.connect( host='xxx.xxx.xxx.xxx', port='3306', user='xxxx', password='xxxxxx', database='test', charset='utf8', cursorclass=pymysql.cursors.DictCursor # 以字典的方式返回數據 ) cur = conn.cursor() # 獲取游標
數據庫表為:
然后要獲取數據庫的數據並返給html頁面,所以app.py代碼:
import pymysql from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): conn = pymysql.connect( host='xxx.xxx.xxx.xxx', port=3306, user='xxxx', password='xxxxxx', database='anne_test', charset='utf8', cursorclass=pymysql.cursors.DictCursor # 以字典的方式返回數據 ) cur = conn.cursor() # 獲取游標 sql = 'select * from test' cur.execute(sql) # 執行sql data = cur.fetchall() # 查詢所有行 cur.close() conn.close() return render_template('index.html',data = data) if __name__ == '__main__': app.run()
html文件index.html代碼:
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>web展示數據庫數據</title> </head> <body> <table> <thead> <tr> <th>id</th> <th>username</th> <th>age</th> <th>sex</th> <th>native</th> </tr> </thead> <tbody> {% for i in data %} <tr> <td>{{ i['id'] }}</td> <td>{{ i['username'] }}</td> <td>{{ i['age'] }}</td> <td>{{ i['sex'] }}</td> <td>{{ i['native'] }}</td> </tr> {% endfor %} </tbody> </table> </body> </html>
html文件必須放在templates文件夾里,不然路由會找不到;
{% for i in data %}表示在data里進行循環,循環必須結束,所以有{% endfor %}
我們可以將data打印出來看一下他的數據結構:
可以看到data是一個列表,它的元素是字典,所以{% for i in data %}里的i就是字典,通過i['key']的方式獲取字典指定key的value,這樣就可以得到具體某個字段的值了
運行app.py,html文件的頁面效果就是這樣的了:
這樣我們就實現了html展示數據庫數據的功能了