代码改变世界

python 从数据库查数据并转为json

2020-09-13 14:58  idea555  阅读(2656)  评论(0)    收藏  举报
from flask import Flask,render_template
import pymysql
import json


app = Flask(__name__)

conn = pymysql.connect('localhost',user = "root",password = "123456",db = "testdb")
cursot = conn.cursor(pymysql.cursors.DictCursor)


@app.route('/')
def hello_world():
dicts = {'name': "lucy", "sex": "boy",'age':18}
dicss1 = [{'name': "lucy", "sex": "boy",'age':18},{'name': "lucy", "sex": "boy",'age':18}]
json_dic = json.dumps(dicss1)
return render_template("show1.html",json_dic = json_dic)

@app.route('/list')
def list():


cursot.execute("select Id,Name,Age,cast(AddTime as char) as date from news")
rows = cursot.fetchall()


#object_list = []
#for row in rows:
# result = {}
# result["Id"] = row[0]
# result["Name"] = row[1]
# result["Age"] = row[2]
# result["AddTime"] = row[3]
# object_list.append(result)


return render_template('show.html',res = json.dumps(rows))
cursot.close()
conn.close()




if __name__ == '__main__':
app.run()