数据库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)
相关推荐
倔强的石头_15 小时前
kingbase备份与恢复实战(二)—— sys_dump库级逻辑备份与恢复(Windows详细步骤)
数据库
jiayou642 天前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
李广坤3 天前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
爱可生开源社区4 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1774 天前
《从零搭建NestJS项目》
数据库·typescript
加号35 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏5 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐5 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
百锦再5 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
QQ5110082855 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php