Python flask框架实现查询数据库并显示数据
更新时间:2020年06月04日 10:01:03 作者:青女素娥
这篇文章主要介绍了Python flask框架实现查询数据库并显示数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
首先数据库长这样

我们想将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文件夹
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Python解决多线程运行异步代码报错"There is no current event loop
在Python开发中,我们经常需要同时处理高并发网络请求和CPU密集型任务,不过当尝试在多线程环境中运行异步代码时,可能会报错"There is no current event loop",下面我们看看具体的解决方法吧2025-04-04
python目录操作之python遍历文件夹后将结果存储为xml
需求是获取服务器某个目录下的某些类型的文件,考虑到服务器即有Linux、又有Windows,所以写了一个Python小程序来完成这项工作,大家参考使用吧2014-01-01


最新评论