数据库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)
相关推荐
tzhou644524 小时前
MySQL备份与恢复
数据库·mysql·adb
一过菜只因5 小时前
MySql Jdbc
android·数据库·mysql
花酒锄作田5 小时前
Flask集成MCP的AI Agent
flask·mcp
思成不止于此5 小时前
MySQL 查询实战(三):排序与综合练习
数据库·笔记·学习·mysql
茅坑的小石头5 小时前
数据库表设计,概念模型、逻辑模型、物理模型的区别,目标、主要内容、所处阶段、面向人群,数据库无关性
数据库
tebukaopu1485 小时前
mysql数据备份还原
数据库·mysql
zyxqyy&∞5 小时前
mysql代码小练-2
数据库·mysql
JIngJaneIL6 小时前
基于Java非遗传承文化管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
+VX:Fegn08956 小时前
计算机毕业设计|基于springboot + vue心理健康管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
only-qi7 小时前
Redis如何应对 Redis 大 Key 问题
数据库·redis·缓存