execute_query
Execute SQL queries on PostgreSQL or MySQL databases to retrieve and manage data, supporting parameterized queries for secure database interactions.
Instructions
Execute a SQL query on the connected database. Returns query results.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | SQL query to execute | |
| params | No | Query parameters (for parameterized queries) |
Implementation Reference
- index.js:331-389 (handler)Implementation of the execute_query tool handler. Executes the provided SQL query on the currently connected PostgreSQL or MySQL database, handles parameterized queries, and returns formatted JSON results including rows, row count, and field information.async executeQuery(query, params) { if (!this.currentConfig) { throw new Error('Not connected to any database. Call connect_database first.'); } if (this.currentConfig.type === 'postgresql') { if (!this.postgresPool) { throw new Error('PostgreSQL connection not initialized'); } const result = await this.postgresPool.query(query, params); return { content: [ { type: 'text', text: JSON.stringify( { rows: result.rows, rowCount: result.rowCount, fields: result.fields.map((f) => ({ name: f.name, dataTypeID: f.dataTypeID, })), }, null, 2 ), }, ], }; } else if (this.currentConfig.type === 'mysql') { if (!this.mysqlConnection) { throw new Error('MySQL connection not initialized'); } const [rows, fields] = await this.mysqlConnection.query(query, params || []); return { content: [ { type: 'text', text: JSON.stringify( { rows: rows, rowCount: Array.isArray(rows) ? rows.length : 0, fields: fields?.map((f) => ({ name: f.name, type: f.type, })) || [], }, null, 2 ), }, ], }; } else { throw new Error(`Unsupported database type: ${this.currentConfig.type}`); } }
- index.js:157-173 (schema)Input schema definition for the execute_query tool, specifying the required 'query' string and optional 'params' array of basic types.inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'SQL query to execute', }, params: { type: 'array', description: 'Query parameters (for parameterized queries)', items: { type: ['string', 'number', 'boolean', 'null'], }, }, }, required: ['query'], },
- index.js:153-174 (registration)Registration of the execute_query tool in the list of available tools returned by ListToolsRequestHandler.{ name: 'execute_query', description: 'Execute a SQL query on the connected database. Returns query results.', inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'SQL query to execute', }, params: { type: 'array', description: 'Query parameters (for parameterized queries)', items: { type: ['string', 'number', 'boolean', 'null'], }, }, }, required: ['query'], }, },