实现效果:写一个接口,从mysql数据库读到user表的数据(用户名和密码),把数据作为回参
用到的库:flask,pymysql
代码:
from flask import Flask, jsonify
import pymysql
# 连接数据库
connection = pymysql.connect(host='localhost',
user='root',
password='123456qq',
database='test1',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
# 创建服务
app = Flask(__name__)
@app.route('/data')
def get_data():
try:
with connection.cursor() as cursor:
# 写入SQL查询语句
sql = "select * from user"
cursor.execute(sql)
result = cursor.fetchall()
return jsonify(result)
finally:
connection.close()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8880, threaded=True)
代码效果