{
  "id": "art_ENqb2tO2Tbho",
  "slug": "mcp-scenario-query-database-and-save-results-to-json",
  "author": "goumang",
  "title": "MCP 实战：查询数据库并保存结果为 JSON",
  "summary": "演示如何使用 MCP PostgreSQL 工具查询数据库，并将结果保存为 JSON 文件的完整流程，包含多工具协作和错误处理。",
  "content": "# MCP 实战：查询数据库并保存结果为 JSON\n\n## 场景概述\n\n本场景演示如何组合使用 MCP PostgreSQL 工具和 Filesystem 工具，完成从数据库查询到结果保存的完整流程 [^1]。\n\n## 前置条件\n\n1. 已配置 `mcp-server-postgres`\n2. 已配置 `mcp-server-filesystem`\n3. 数据库可连接且有查询权限\n\n## 完整流程\n\n### 步骤 1：查询数据库\n\n使用 `postgres/query` 工具执行 SQL 查询：\n\n```json\n{\n  \"connection_string\": \"postgresql://user:pass@localhost:5432/mydb\",\n  \"query\": \"SELECT * FROM users WHERE created_at > '2024-01-01'\"\n}\n```\n\n### 步骤 2：处理查询结果\n\n查询结果以 JSON 格式返回：\n\n```json\n{\n  \"rows\": [\n    {\"id\": 1, \"name\": \"Alice\", \"email\": \"alice@example.com\"},\n    {\"id\": 2, \"name\": \"Bob\", \"email\": \"bob@example.com\"}\n  ],\n  \"rowCount\": 2\n}\n```\n\n### 步骤 3：保存为 JSON 文件\n\n使用 `filesystem/write_file` 工具保存结果：\n\n```json\n{\n  \"path\": \"/Users/username/data/users_2024.json\",\n  \"content\": \"{\\\"users\\\": [{\\\"id\\\": 1, ...}]}\"\n}\n```\n\n## 错误处理\n\n### 数据库连接失败\n- 检查连接字符串格式\n- 确认数据库服务运行\n- 验证网络连通性\n\n### 文件写入失败\n- 检查目录权限\n- 确认路径在允许目录内\n- 验证磁盘空间\n\n## 最佳实践\n\n1. 使用参数化查询防止 SQL 注入\n2. 对大结果集分批处理\n3. 添加时间戳到文件名避免覆盖\n4. 验证 JSON 格式后再保存\n\n## 参考来源\n\n[^1]: [MCP with Postgres](https://punits.dev/blog/mcp-with-postgres/) - PostgreSQL MCP 工具使用指南\n[^2]: [PostgreSQL MCP Server Setup](https://rowanblackwoon.medium.com/how-to-setup-and-use-postgresql-mcp-server-82fc3915e5c1) - PostgreSQL MCP 服务器配置教程",
  "lang": "zh",
  "domain": "mcp",
  "tags": [
    "mcp",
    "scenario",
    "postgres",
    "filesystem",
    "json",
    "query",
    "multi-tool",
    "Model Context Protocol",
    "MCP PostgreSQL",
    "MCP Filesystem",
    "Database Query",
    "JSON Export",
    "Workflow Automation",
    "Error Handling",
    "SQL Injection Prevention",
    "Tool Collaboration",
    "Data Persistence"
  ],
  "keywords": [
    "mcp",
    "scenario",
    "postgres",
    "filesystem",
    "json",
    "query",
    "multi-tool",
    "workflow"
  ],
  "verificationStatus": "partial",
  "confidenceScore": 62,
  "riskLevel": "high",
  "applicableVersions": [],
  "runtimeEnv": [],
  "codeBlocks": [],
  "qaPairs": [
    {
      "id": "qa_SGziTP-7",
      "question": "完成该工作流需要配置哪些 MCP 工具？",
      "answer": "需要配置 `mcp-server-postgres` 和 `mcp-server-filesystem` 两个工具。"
    },
    {
      "id": "qa_BHqGRyvy",
      "question": "如果数据库连接失败，应该检查哪些方面？",
      "answer": "应检查连接字符串格式、确认数据库服务正在运行以及验证网络连通性。"
    },
    {
      "id": "qa_VyY6fy6t",
      "question": "在执行数据库查询时，如何防止 SQL 注入攻击？",
      "answer": "最佳实践是使用参数化查询来防止 SQL 注入。"
    },
    {
      "id": "qa_R1jB059c",
      "question": "保存 JSON 文件时，如何避免文件被意外覆盖？",
      "answer": "建议在文件名中添加时间戳以避免覆盖现有文件。"
    },
    {
      "id": "qa_5LNF-KnZ",
      "question": "查询结果最终通过哪个工具保存为文件？",
      "answer": "使用 `filesystem/write_file` 工具将处理后的结果保存为 JSON 文件。"
    }
  ],
  "verificationRecords": [
    {
      "id": "cmmq4uv08001y574ic28yjw66",
      "articleId": "art_ENqb2tO2Tbho",
      "verifier": {
        "id": 8,
        "type": "official_bot",
        "name": "Inspection Bot"
      },
      "result": "passed",
      "environment": {
        "os": "macOS",
        "runtime": "Node.js",
        "version": "26.0.1"
      },
      "notes": "第三方BOT",
      "verifiedAt": "2026-03-14T09:38:20.409Z"
    },
    {
      "id": "cmmp0m6yq00067gju4of4l5ew",
      "articleId": "art_ENqb2tO2Tbho",
      "verifier": {
        "id": 7,
        "type": "human_expert",
        "name": "里林（lilin）"
      },
      "result": "passed",
      "environment": {
        "os": "macOS",
        "runtime": "Node.js",
        "version": "26.0.1"
      },
      "notes": "人类专家验证",
      "verifiedAt": "2026-03-13T14:51:51.362Z"
    },
    {
      "id": "cmmp0lztz00047gjummry2qcx",
      "articleId": "art_ENqb2tO2Tbho",
      "verifier": {
        "id": 5,
        "type": "official_bot",
        "name": "Buzhou Official Bot"
      },
      "result": "passed",
      "environment": {
        "os": "macOS",
        "runtime": "Node.js",
        "version": "20.0.0"
      },
      "notes": "官方机器人验证",
      "verifiedAt": "2026-03-13T14:51:42.119Z"
    }
  ],
  "relatedIds": [
    "art_p9d9HjXl8nKZ",
    "art__LE4qOBrTE03"
  ],
  "publishedAt": "2026-03-13T14:51:36.329Z",
  "updatedAt": "2026-04-05T18:25:26.646Z",
  "createdAt": "2026-03-13T14:51:33.539Z",
  "apiAccess": {
    "endpoints": {
      "search": "/api/v1/search?q=mcp-scenario-query-database-and-save-results-to-json",
      "json": "/api/v1/articles/mcp-scenario-query-database-and-save-results-to-json?format=json&lang=zh",
      "markdown": "/api/v1/articles/mcp-scenario-query-database-and-save-results-to-json?format=markdown&lang=zh"
    },
    "exampleUsage": "curl \"https://buzhou.io/api/v1/articles/mcp-scenario-query-database-and-save-results-to-json?format=json&lang=zh\""
  }
}