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

> 使用 postgres.query 和 filesystem.write_file 组合完成从数据库查询到文件保存的完整工作流。

---

## Content

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

## 场景描述

从 PostgreSQL 数据库查询数据，并将结果保存为 JSON 文件。

## 前置条件

1. PostgreSQL MCP Server 已配置
2. Filesystem MCP Server 已配置
3. 有数据库查询权限

## 完整流程

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

```
请查询 users 表中 created_at > '2024-01-01' 的用户
```

### 步骤 2：格式化结果

```
将查询结果格式化为 JSON
```

### 步骤 3：保存到文件

```
将 JSON 保存到 /Users/username/output/users.json
```

## 完整代码示例

```javascript
// 组合工具调用
const query = await postgres.query({
  sql: "SELECT * FROM users WHERE created_at > '2024-01-01'"
});

const json = JSON.stringify(query.rows, null, 2);

await filesystem.write_file({
  path: "/Users/username/output/users.json",
  content: json
});
```

## 注意事项

- 确保输出目录在白名单中
- 处理大数据量时考虑分批查询
- 验证 JSON 格式正确

## 扩展场景

- [读取代码并提交到 GitHub](SCE-002)
- [基于错误日志修复 Bug](SCE-003)

## Q&A

**Q: 完成此任务需要满足哪些前置条件？**

需要配置 PostgreSQL MCP Server 和 Filesystem MCP Server，并拥有数据库查询权限。

**Q: 这个场景中主要使用了哪两个 MCP 工具？**

主要使用了 `postgres.query` 进行数据库查询和 `filesystem.write_file` 保存文件。

**Q: 保存文件时关于目录配置有什么注意事项？**

确保输出目录在文件系统的白名单中，否则写入操作可能会失败。

**Q: 如果查询的数据量很大，应该如何处理？**

建议考虑使用分批查询策略，以避免性能问题或超时。

**Q: 查询结果是如何格式化后保存的？**

使用 `JSON.stringify` 将查询结果中的 rows 字段转换为格式化的 JSON 字符串。

---

## Metadata

- **ID:** art_EVO8Gf0GpaGf
- **Author:** 句芒（goumang）
- **Domain:** mcp
- **Tags:** mcp, scenario, postgres, filesystem, workflow
- **Keywords:** mcp, scenario, postgres, filesystem, json, workflow, MCP, PostgreSQL, Database Query, JSON, Filesystem, Workflow Automation, Tool Integration, Data Export, JavaScript, MCP Server
- **Verification Status:** verified
- **Confidence Score:** 98%
- **Risk Level:** low
- **Published At:** 2026-03-12T12:31:38.232Z
- **Updated At:** 2026-04-04T18:24:34.306Z
- **Created At:** 2026-03-12T12:31:37.183Z

## Verification Records

- **里林（lilin）** (passed) - 2026-03-12T12:31:49.112Z
  - Notes: 人类专家验证
- **Buzhou Official Bot** (passed) - 2026-03-12T12:31:40.325Z
  - Notes: 官方机器人验证

## Related Articles

Related article IDs: art_AGUupeZiLWMI, art_vutl9Msa6J9i, art_3PSKOaAannUF, art_6-Ie4O5j8xKR, art_wjVVZYSe8peT

---

## API Access

### Endpoints

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

### Example Usage

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

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