insert_data
Insert records into a MySQL table by providing a table name and a dictionary of field-value pairs. Optionally specify database connection configuration for custom setups.
Instructions
向表中插入数据
Args:
table_name: 表名
data: 要插入的数据,字段名和值的字典
db_config: 数据库连接配置参数,如果为None则使用默认配置
Returns:
包含插入结果的字典Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| table_name | Yes | ||
| data | Yes | ||
| db_config | No |
Implementation Reference
- mysql-mcp.py:299-349 (handler)The async function `insert_data` that executes the tool logic. It is decorated with @mcp.tool(), connects to MySQL, builds an INSERT SQL statement from the provided data dict, executes it, commits, and returns the result with inserted_id. Includes error handling for common MySQL errors.
@mcp.tool() async def insert_data(table_name: str, data: Dict[str, Any], db_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: """向表中插入数据 Args: table_name: 表名 data: 要插入的数据,字段名和值的字典 db_config: 数据库连接配置参数,如果为None则使用默认配置 Returns: 包含插入结果的字典 """ if not table_name or not data: return {"error": "表名和数据不能为空"} try: conn = get_connection(db_config) cursor = conn.cursor() columns = ", ".join(data.keys()) placeholders = ", ".join(["%s"] * len(data)) values = list(data.values()) insert_sql = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})" cursor.execute(insert_sql, values) conn.commit() return { "success": True, "inserted_id": cursor.lastrowid, "message": f"数据成功插入到表 {table_name}" } except Error as e: error_message = f"插入数据失败: {str(e)}" if "doesn't exist" in str(e): error_message += f"\n原因:表 {table_name} 不存在" elif "Unknown column" in str(e): error_message += "\n原因:插入数据中包含表中不存在的列" elif "cannot be null" in str(e): error_message += "\n原因:某个NOT NULL字段被设置为NULL值" elif "Duplicate entry" in str(e): error_message += "\n原因:插入的数据违反了唯一键约束" elif "Data too long" in str(e): error_message += "\n原因:插入的数据超出了字段的长度限制" return {"error": error_message} except Exception as e: return {"error": f"插入数据时发生未知错误: {str(e)}"} finally: if 'conn' in locals() and conn.is_connected(): cursor.close() conn.close() - mysql-mcp.py:299-299 (registration)The @mcp.tool() decorator on line 299 registers `insert_data` as an MCP tool with the FastMCP server instance named 'mcp'.
@mcp.tool()