# MCP Scenario: Query Database and Save Results to JSON

> Demonstrates the complete workflow of using MCP PostgreSQL tool to query database and save results as JSON file, including multi-tool collaboration and error handling.

---

## Content

# MCP Scenario: Query Database and Save Results to JSON

## Scenario Overview

This scenario demonstrates how to combine MCP PostgreSQL tool and Filesystem tool to complete the workflow from database query to result saving [^1].

## Prerequisites

1. `mcp-server-postgres` configured
2. `mcp-server-filesystem` configured
3. Database accessible with query permissions

## Complete Workflow

### Step 1: Query Database

Use `postgres/query` tool to execute SQL query:

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

### Step 2: Process Query Results

Query results returned in JSON format:

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

### Step 3: Save as JSON File

Use `filesystem/write_file` tool to save results:

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

## Error Handling

### Database Connection Failure
- Check connection string format
- Confirm database service running
- Verify network connectivity

### File Write Failure
- Check directory permissions
- Confirm path within allowed directories
- Verify disk space

## Best Practices

1. Use parameterized queries to prevent SQL injection
2. Process large result sets in batches
3. Add timestamps to filenames to avoid overwriting
4. Validate JSON format before saving

## Reference Sources

[^1]: [MCP with Postgres](https://punits.dev/blog/mcp-with-postgres/) - PostgreSQL MCP tool usage guide
[^2]: [PostgreSQL MCP Server Setup](https://rowanblackwoon.medium.com/how-to-setup-and-use-postgresql-mcp-server-82fc3915e5c1) - PostgreSQL MCP server configuration tutorial

## Q&A

**Q: Which MCP tools need to be configured to complete this workflow?**

You need to configure both `mcp-server-postgres` and `mcp-server-filesystem` tools.

**Q: What should be checked if the database connection fails?**

Check the connection string format, confirm the database service is running, and verify network connectivity.

**Q: How to prevent SQL injection attacks when executing database queries?**

The best practice is to use parameterized queries to prevent SQL injection.

**Q: How to avoid accidental file overwriting when saving JSON files?**

It is recommended to add timestamps to the filename to avoid overwriting existing files.

**Q: Which tool is ultimately used to save the query results as a file?**

Use the `filesystem/write_file` tool to save the processed results as a JSON file.

---

## 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"
```
