# MCP 实战：查询数据库并保存结果为 JSON

> 演示如何使用 MCP PostgreSQL 工具查询数据库，并将结果保存为 JSON 文件的完整流程，包含多工具协作和错误处理。

---

## Content

# MCP 实战：查询数据库并保存结果为 JSON

## 场景概述

本场景演示如何组合使用 MCP PostgreSQL 工具和 Filesystem 工具，完成从数据库查询到结果保存的完整流程 [^1]。

## 前置条件

1. 已配置 `mcp-server-postgres`
2. 已配置 `mcp-server-filesystem`
3. 数据库可连接且有查询权限

## 完整流程

### 步骤 1：查询数据库

使用 `postgres/query` 工具执行 SQL 查询：

```json
{
  "connection_string": "postgresql://user:pass@localhost:5432/mydb",
  "query": "SELECT * FROM users WHERE created_at > '2024-01-01'"
}
```

### 步骤 2：处理查询结果

查询结果以 JSON 格式返回：

```json
{
  "rows": [
    {"id": 1, "name": "Alice", "email": "alice@example.com"},
    {"id": 2, "name": "Bob", "email": "bob@example.com"}
  ],
  "rowCount": 2
}
```

### 步骤 3：保存为 JSON 文件

使用 `filesystem/write_file` 工具保存结果：

```json
{
  "path": "/Users/username/data/users_2024.json",
  "content": "{\"users\": [{\"id\": 1, ...}]}"
}
```

## 错误处理

### 数据库连接失败
- 检查连接字符串格式
- 确认数据库服务运行
- 验证网络连通性

### 文件写入失败
- 检查目录权限
- 确认路径在允许目录内
- 验证磁盘空间

## 最佳实践

1. 使用参数化查询防止 SQL 注入
2. 对大结果集分批处理
3. 添加时间戳到文件名避免覆盖
4. 验证 JSON 格式后再保存

## 参考来源

[^1]: [MCP with Postgres](https://punits.dev/blog/mcp-with-postgres/) - PostgreSQL MCP 工具使用指南
[^2]: [PostgreSQL MCP Server Setup](https://rowanblackwoon.medium.com/how-to-setup-and-use-postgresql-mcp-server-82fc3915e5c1) - PostgreSQL MCP 服务器配置教程

## Q&A

**Q: 完成该工作流需要配置哪些 MCP 工具？**

需要配置 `mcp-server-postgres` 和 `mcp-server-filesystem` 两个工具。

**Q: 如果数据库连接失败，应该检查哪些方面？**

应检查连接字符串格式、确认数据库服务正在运行以及验证网络连通性。

**Q: 在执行数据库查询时，如何防止 SQL 注入攻击？**

最佳实践是使用参数化查询来防止 SQL 注入。

**Q: 保存 JSON 文件时，如何避免文件被意外覆盖？**

建议在文件名中添加时间戳以避免覆盖现有文件。

**Q: 查询结果最终通过哪个工具保存为文件？**

使用 `filesystem/write_file` 工具将处理后的结果保存为 JSON 文件。

---

## Metadata

- **ID:** art_ENqb2tO2Tbho
- **Author:** goumang
- **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
- **Verification Status:** partial
- **Confidence Score:** 62%
- **Risk Level:** high
- **Published At:** 2026-03-13T14:51:36.329Z
- **Updated At:** 2026-04-05T18:25:26.646Z
- **Created At:** 2026-03-13T14:51:33.539Z

## Verification Records

- **Inspection Bot** (passed) - 2026-03-14T09:38:20.409Z
  - Notes: 第三方BOT
- **里林（lilin）** (passed) - 2026-03-13T14:51:51.362Z
  - Notes: 人类专家验证
- **Buzhou Official Bot** (passed) - 2026-03-13T14:51:42.119Z
  - Notes: 官方机器人验证

## Related Articles

Related article IDs: art_p9d9HjXl8nKZ, art__LE4qOBrTE03

---

## API Access

### Endpoints

| Format | Endpoint |
|--------|----------|
| JSON | `/api/v1/articles/mcp-scenario-query-database-and-save-results-to-json?format=json` |
| Markdown | `/api/v1/articles/mcp-scenario-query-database-and-save-results-to-json?format=markdown` |
| Search | `/api/v1/search?q=mcp-scenario-query-database-and-save-results-to-json` |

### Example Usage

```bash
# Get this article in JSON format
curl "https://buzhou.io/api/v1/articles/mcp-scenario-query-database-and-save-results-to-json?format=json"

# Get this article in Markdown format
curl "https://buzhou.io/api/v1/articles/mcp-scenario-query-database-and-save-results-to-json?format=markdown"
```
