# MySQL - Query

> 在 MySQL 和 MariaDB 数据库上执行 SQL 查询。

Source: https://docs.sommatic.ai/zh/nodes/integrations.oracle.mysql.query/

- 标识: `integrations.oracle.mysql.query`
- 类别: 集成
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

在 MySQL 和 MariaDB 数据库上执行 SQL 查询。

连接你的 MySQL 实例，使用位置参数 ? 绑定运行参数化查询以防止 SQL 注入。兼容 MySQL、MariaDB 及类似数据库。

**操作：**
- **SELECT：** 通过过滤、连接和聚合从表中获取行。
- **INSERT：** 向表中添加新记录。
- **UPDATE：** 修改满足条件的现有记录。
- **DELETE：** 从表中删除记录。
- **存储过程：** 通过 CALL 语句调用存储过程。
- **DDL：** 执行 CREATE、ALTER、DROP 语句以管理 schema。

## 配置

- `connection_id` (string, 必填): MySQL 实例的凭据。接受 `connection-string`（mysql:// URI）或 `basic-auth`（用户名 + 密码 + 主机 + 数据库）类型的凭据。
- `sql` (string, 必填, 支持表达式): 要执行的 SQL 语句（例如“SELECT * FROM users WHERE id = ?”）。
- `parameters` (array, 可选): 用于位置参数 ? 绑定的值数组。

## 输出端口

- `out` (默认): 查询返回的结果行
- `error`: 执行期间发生错误

## 输入契约

- `connection_id` (string, 必填)
- `sql` (string, 必填)
- `parameters` (array, 可选)

## 输出契约

- `result` (array<object>, 可选): 查询返回的行数组

## 在表达式中

后续节点可通过 `$("MySQL - Query").item.json.<路径>` 读取此节点输出中的内容（请把 `MySQL - Query` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("MySQL - Query").item.json.result` (array) = `[…] (1)`: 查询返回的行数组


## 工作原理

在 MySQL 上执行一条带位置参数 `?` 的预处理 SQL 语句，并将结果行（或写操作结果）放在 `result` 中返回。

1. 解析节点配置中的表达式。`connection_id`、`sql` 为空时从输入项读取。参数从未声明的 `params` 键读取，其次是输入项的 `parameters`；已声明的 `parameters` 配置键不会被读取。
2. 解析连接：`connection_id` 中的 `mysql://` / `mysql2://` URI、`connection-string` 凭据，或包含 `username`、`password`、`host`、`database`、`port`（默认 3306）的 `basic-auth` / `object` 凭据。日期以字符串返回。
3. 以预处理语句方式使用参数执行 `sql`（单个值会被包装成数组），然后关闭连接。
4. 经 `out` 返回 `{ result }`：SELECT 时为结果行（无结果时为空数组），写操作时为驱动的结果头（`affectedRows`、`insertId` 等）。

## 在工作流中

### 节点

```json
{
  "node_id": "node-find-customer",
  "label": "Find customer",
  "operator_slug": "integrations.oracle.mysql.query",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "sql": "SELECT id, email, created_at FROM customers WHERE email = ?",
    "params": [
      "{{ $json.email }}"
    ]
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": [
      {
        "id": 42,
        "email": "ana@example.com",
        "created_at": "2026-11-20 15:04:05"
      }
    ]
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

语句已执行，无论是否返回行。

```json
{
  "result": [
    {
      "id": 42,
      "email": "ana@example.com",
      "created_at": "2026-11-20 15:04:05"
    }
  ]
}
```

### `error`

校验、凭据解析、连接或语句执行失败。

```json
{
  "error": "Incorrect arguments to mysqld_stmt_execute"
}
```

## 代码中的行为

- `parameters`: 已在 schema 中声明，但 worker 不会读取。请将参数值写在 `params` 中。
- `params`: 未声明的键，用于存放 `?` 的位置参数值。非数组值会作为单个参数发送。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `connection_id is required` | `error` | 配置和输入项中都没有凭据。 |
| `sql query is required` | `error` | `sql` 为空。 |
| `Incorrect arguments to mysqld_stmt_execute` | `error` | 参数数量与 `?` 占位符不一致。常见原因：值写在了本节点会忽略的 `parameters` 中，请改用 `params`。 |
| `Credential <connection_id> has unsupported type '<type>' for integrations.oracle.mysql.query. Use 'connection-string' or 'basic-auth'.` | `error` | 本节点不支持该凭据类型。 |

## 说明与限制

- 没有 `empty` 端口：无结果的 SELECT 经 `out` 输出，`result` 为 `[]`。
- 每次运行都会新建并关闭连接，节点不会重试。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "integrations.oracle.mysql.query",
  "name": "MySQL - Query",
  "category": "integrations",
  "version": "1.0.0",
  "description": "Execute SQL queries on MySQL and MariaDB databases.\n\n  Connect your MySQL instance and run parameterized queries with positional ? binding for SQL injection prevention. Compatible with MySQL, MariaDB, and similar databases.\n\n  **Operations:**\n  - **SELECT:** Fetch rows from tables with filters, joins, and aggregations.\n  - **INSERT:** Add new records to tables.\n  - **UPDATE:** Modify existing records matching a condition.\n  - **DELETE:** Remove records from tables.\n  - **Stored Procedures:** Call stored procedures via CALL statements.\n  - **DDL:** Execute CREATE, ALTER, DROP statements for schema management.",
  "capabilities": [
    "sql",
    "database",
    "mysql",
    "mariadb"
  ],
  "group": [
    {
      "key": "oracle",
      "name": "Oracle",
      "icon_url": "/icons/integrations/oracle/oracle.svg"
    },
    {
      "key": "mysql",
      "name": "MySQL",
      "icon_url": "/icons/integrations/oracle/mysql.svg"
    }
  ],
  "icon_url": "/icons/integrations/oracle/mysql.svg",
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "MySQL Credential",
        "description": "Credential for your MySQL instance. Accepts credentials of type `connection-string` (mysql:// URI) or `basic-auth` (username + password + host + database).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "connection-string",
            "basic-auth"
          ],
          "types": [
            "mysql"
          ]
        }
      },
      "sql": {
        "type": "string",
        "title": "SQL Query",
        "description": "The SQL statement to execute (e.g., \"SELECT * FROM users WHERE id = ?\").",
        "format": "expression",
        "ui_widget": "sql_editor"
      },
      "parameters": {
        "type": "array",
        "title": "Query Parameters",
        "description": "Array of values for positional ? parameter binding."
      }
    },
    "required": [
      "connection_id",
      "sql"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "sql": {
        "type": "string"
      },
      "parameters": {
        "type": "array"
      }
    },
    "required": [
      "connection_id",
      "sql"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "array",
        "items": {
          "type": "object"
        },
        "description": "Array of rows returned by the query"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Rows",
      "description": "Resulting rows from the query",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Error occurred during execution",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "db-io"
  ],
  "tags": [
    "sql",
    "database"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://sommatic.ai",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "MySQL Credential",
      "description": "Credential for your MySQL instance. Accepts credentials of type `connection-string` (mysql:// URI) or `basic-auth` (username + password + host + database).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "connection-string",
          "basic-auth"
        ],
        "types": [
          "mysql"
        ]
      }
    },
    "sql": {
      "type": "string",
      "title": "SQL Query",
      "description": "The SQL statement to execute (e.g., \"SELECT * FROM users WHERE id = ?\").",
      "format": "expression",
      "ui_widget": "sql_editor"
    },
    "parameters": {
      "type": "array",
      "title": "Query Parameters",
      "description": "Array of values for positional ? parameter binding."
    }
  },
  "required": [
    "connection_id",
    "sql"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "sql": {
      "type": "string"
    },
    "parameters": {
      "type": "array"
    }
  },
  "required": [
    "connection_id",
    "sql"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "array",
      "items": {
        "type": "object"
      },
      "description": "Array of rows returned by the query"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Rows",
    "description": "Resulting rows from the query",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Error occurred during execution",
    "is_default": false,
    "supports_condition": false
  }
]
```
