mysql_query
Execute SQL queries directly on MySQL databases using the MCP Server. Input SQL statements and optional parameters for precise data retrieval and database operations.
Instructions
执行 SQL 查询
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| params | No | 参数化查询的参数(可选) | |
| sql | Yes | SQL 查询语句 |
Input Schema (JSON Schema)
{
"properties": {
"params": {
"description": "参数化查询的参数(可选)",
"items": {
"type": "string"
},
"type": "array"
},
"sql": {
"description": "SQL 查询语句",
"type": "string"
}
},
"required": [
"sql"
],
"type": "object"
}
Implementation Reference
- src/server.ts:395-407 (handler)The primary handler for the mysql_query tool. It validates the input SQL, executes the query via DatabaseManager, formats the result message, and returns the query rows as JSON in text content.private async handleQuery(args: { sql: string; params?: any[] }): Promise<any> { validateSQL(args.sql); const result = await this.dbManager.query(args.sql, args.params); return { content: [ { type: 'text', text: `${formatQueryResult(result)}\n\n查询结果:\n${JSON.stringify(result.rows, null, 2)}`, }, ], }; }
- src/server.ts:139-154 (schema)The tool registration entry including name, description, and input schema for mysql_query in the ListTools response.{ name: 'mysql_query', description: '执行 SQL 查询', inputSchema: { type: 'object', properties: { sql: { type: 'string', description: 'SQL 查询语句' }, params: { type: 'array', description: '参数化查询的参数(可选)', items: { type: 'string' } }, }, required: ['sql'], }, },
- src/database.ts:51-77 (helper)Core query execution helper in DatabaseManager that uses mysql2 pool.execute to run the SQL with optional params, handling both row results and affected rows.async query(sql: string, params?: any[]): Promise<QueryResult> { if (!this.pool) { throw new Error('数据库未连接,请先调用 connect() 方法'); } try { const [rows, fields] = await this.pool.execute(sql, params); if (Array.isArray(rows)) { return { rows: rows as any[], fields: fields as any[] }; } else { // 对于 INSERT, UPDATE, DELETE 等操作 const result = rows as mysql.ResultSetHeader; return { rows: [], fields: [], affectedRows: result.affectedRows, insertId: result.insertId }; } } catch (error) { throw new Error(`SQL 执行失败: ${error instanceof Error ? error.message : String(error)}`); } }
- src/utils.ts:79-93 (helper)SQL validation helper used in mysql_query handler to detect potentially dangerous SQL patterns like DROP DATABASE or WHERE-less DELETE/UPDATE.export function validateSQL(sql: string): void { const dangerousPatterns = [ /drop\s+database/i, /drop\s+schema/i, /truncate\s+table/i, /delete\s+from.*where\s*$/i, // DELETE without WHERE /update.*set.*where\s*$/i, // UPDATE without WHERE ]; for (const pattern of dangerousPatterns) { if (pattern.test(sql.trim())) { throw new Error('检测到潜在危险的 SQL 语句,请谨慎操作'); } } }
- src/utils.ts:64-74 (helper)Formats the query result message for the response text in mysql_query handler.export function formatQueryResult(result: QueryResult): string { if (result.affectedRows !== undefined) { return `操作完成,影响行数: ${result.affectedRows}${result.insertId ? `,插入ID: ${result.insertId}` : ''}`; } if (result.rows.length === 0) { return '查询结果为空'; } return `查询成功,返回 ${result.rows.length} 行数据`; }