数据库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)
相关推荐
l1t3 分钟前
DeepSeek辅助编写连接sqlite的CLI
数据库·golang·sqlite
翔云1234564 分钟前
Gaea中配置如何更新
运维·数据库·mysql
泡海椒1 小时前
JQuick-SQL JQuickTable 模型:XML 动态 SQL 的表封装边界
xml·数据库·sql
ss2732 小时前
AI时代首先数据库-PostgreSQL实战笔记 | 28 PostgreSQL MVCC机制介绍
数据库·笔记·postgresql
奇牙coding2 小时前
doubao-seed-2.1-pro 报 HTTP 401 怎么办?Key 正确也要检查请求头和端点
网络·数据库·http·ai
不脱发的程序猿10 小时前
纳指ETF量化策略
数据库·人工智能·1024程序员节
程序员塔塔喵11 小时前
【MySQL篇|第一篇】索引失效的情况
数据库·mysql·索引失效
北京青蓝智慧马老师12 小时前
比外部黑客更难防的,是那个有权限的自己人(3 个脱敏复盘)
大数据·数据库·人工智能
笃行35012 小时前
拆一台数据集成产品:KFS 的骨架、肌肉和神经
数据库
4SAPI12 小时前
搭建 AI 数据分析工具大模型 API 选型指南
数据库·人工智能·架构·php·1024程序员节