数据库flask访问

执行节点

python 复制代码
import urllib.request
import json

def main(sql: str) -> dict:
    api_url = "http://192.168.0.108:35003/execute_query"
    headers = {"Content-Type": "application/json"}
    data = json.dumps({"sql": sql}).encode("utf-8")

    try:
        req = urllib.request.Request(api_url, data=data, headers=headers, method="POST")
        with urllib.request.urlopen(req) as response:
            res_data = json.loads(response.read().decode("utf-8"))
        
        # 转成 JSON 字符串返回
        return {"result": json.dumps(res_data)}
    except Exception as e:
        # 异常信息也返回字符串
        return {"result": f"请求接口失败: {str(e)}"}

app.py

运行方法:

yum install -y python3

pip3 install flask pymysql

python3 app.py

firewall-cmd --add-port=35003/tcp --permanent

firewall-cmd --reload

python 复制代码
from flask import Flask, request, jsonify
import pymysql

app = Flask(__name__)

@app.route("/execute_query", methods=['GET', 'POST'])
def execute_query():
    data = request.get_json()
    sql = data.get("sql", "").strip()

    if not sql:
        return jsonify({"error": "SQL语句不能为空"}), 400
    if not sql.lower().startswith("select"):
        return jsonify({"error": "只允许执行SELECT语句"}), 400

    try:
        # 建立数据库连接
        conn = pymysql.connect(
            host="192.168.0.108",  # 你的数据库IP
            user="root",
            password="123456",
            database="mydb",
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn.cursor() as cursor:
            cursor.execute(sql)
            result = cursor.fetchall()
        conn.close()

        return jsonify(result)

    except pymysql.Error as e:
        return jsonify({"error": f"数据库错误: {str(e)}"}), 500
    except Exception as e:
        return jsonify({"error": f"未知错误: {str(e)}"}), 500


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=35003)
相关推荐
清水白石00829 分钟前
解构异步编程的两种哲学:从 asyncio 到 Trio,理解 Nursery 的魔力
运维·服务器·数据库·python
资生算法程序员_畅想家_剑魔31 分钟前
Mysql常见报错解决分享-01-Invalid escape character in string.
数据库·mysql
PyHaVolask1 小时前
SQL注入漏洞原理
数据库·sql
ptc学习者1 小时前
黑格尔时代后崩解的辩证法
数据库
代码游侠1 小时前
应用——智能配电箱监控系统
linux·服务器·数据库·笔记·算法·sqlite
!chen2 小时前
EF Core自定义映射PostgreSQL原生函数
数据库·postgresql
霖霖总总2 小时前
[小技巧14]MySQL 8.0 系统变量设置全解析:SET GLOBAL、SET PERSIST 与 SET PERSIST_ONLY 的区别与应用
数据库·mysql
马克学长2 小时前
SSM校园食堂订餐系统531p9(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·ssm 框架·ssm 校园食堂订餐系统
alonewolf_992 小时前
深入剖析MySQL索引底层:B+树、联合索引与跳跃扫描原理全解
数据库·b树·mysql
oMcLin2 小时前
如何在 AlmaLinux 9 上配置并优化 Redis 集群,支持高并发的实时数据缓存与快速查询?
数据库·redis·缓存