mysql_export_data
Export MySQL table data to CSV or JSON files with optional filtering, enabling data backup, migration, or analysis.
Instructions
导出表数据到文件
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| tableName | Yes | 表名称 | |
| filePath | Yes | 导出文件路径 | |
| format | Yes | 导出格式 | |
| where | No | 查询条件(可选) |
Implementation Reference
- src/server.ts:471-488 (handler)The main handler function for mysql_export_data tool. Constructs a SELECT query, executes it via dbManager, exports the result using exportData helper, and returns success message.private async handleExportData(args: { tableName: string; filePath: string; format: 'csv' | 'json'; where?: string }): Promise<any> { let sql = `SELECT * FROM \`${args.tableName}\``; if (args.where) { sql += ` WHERE ${args.where}`; } const result = await this.dbManager.query(sql); await exportData(result, { format: args.format, filePath: args.filePath }); return { content: [ { type: 'text', text: `成功导出 ${result.rows.length} 行数据到文件: ${args.filePath}`, }, ], }; }
- src/types.ts:43-47 (schema)Type definition for ExportOptions used in the exportData helper function.export interface ExportOptions { format: 'csv' | 'json'; filePath: string; includeHeaders?: boolean; }
- src/server.ts:196-209 (registration)Tool registration in the ListToolsRequestSchema handler, including name, description, and inputSchema definition.{ name: 'mysql_export_data', description: '导出表数据到文件', inputSchema: { type: 'object', properties: { tableName: { type: 'string', description: '表名称' }, filePath: { type: 'string', description: '导出文件路径' }, format: { type: 'string', enum: ['csv', 'json'], description: '导出格式' }, where: { type: 'string', description: '查询条件(可选)' }, }, required: ['tableName', 'filePath', 'format'], }, },
- src/utils.ts:11-35 (helper)Helper function that performs the actual data export to CSV or JSON file, called by the handler.export async function exportData(data: QueryResult, options: ExportOptions): Promise<void> { const { format, filePath, includeHeaders = true } = options; // 确保目录存在 const dir = path.dirname(filePath); await fs.mkdir(dir, { recursive: true }); if (format === 'json') { await fs.writeFile(filePath, JSON.stringify(data.rows, null, 2), 'utf-8'); } else if (format === 'csv') { if (data.rows.length === 0) { await fs.writeFile(filePath, '', 'utf-8'); return; } const headers = Object.keys(data.rows[0]).map(key => ({ id: key, title: key })); const csvWriter = createObjectCsvWriter({ path: filePath, header: headers, encoding: 'utf8' }); await csvWriter.writeRecords(data.rows); } }