Python flask框架实现查询数据库并显示数据

2020-10-05 0 954

首先数据库长这样

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>

运行结果

Python flask框架实现查询数据库并显示数据

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

遇见资源网 Python Python flask框架实现查询数据库并显示数据 http://www.ox520.com/25917.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务