(self, config: dict, context: ExecutionContext)
| 250 | return "db_update" |
| 251 | |
| 252 | async def execute(self, config: dict, context: ExecutionContext) -> ModuleResult: |
| 253 | connection_name = context.resolve_value(config.get('connectionName', 'default')) |
| 254 | table = context.resolve_value(config.get('table', '')) |
| 255 | data = config.get('data', {}) |
| 256 | where = context.resolve_value(config.get('where', '')) |
| 257 | variable_name = context.resolve_value(config.get('variableName', '')) |
| 258 | |
| 259 | connections = get_db_connections(context) |
| 260 | conn = connections.get(connection_name) |
| 261 | |
| 262 | if not conn: |
| 263 | return ModuleResult( |
| 264 | success=False, |
| 265 | error=f"数据库连接 '{connection_name}' 不存在,请先使用「连接数据库」模块" |
| 266 | ) |
| 267 | |
| 268 | if not table: |
| 269 | return ModuleResult(success=False, error="请指定表名") |
| 270 | |
| 271 | try: |
| 272 | # 解析数据 |
| 273 | if isinstance(data, str): |
| 274 | import json |
| 275 | data = json.loads(context.resolve_value(data)) |
| 276 | |
| 277 | # 解析数据中的变量 |
| 278 | resolved_data = {} |
| 279 | for key, value in data.items(): |
| 280 | if isinstance(value, str): |
| 281 | resolved_data[key] = context.resolve_value(value) |
| 282 | else: |
| 283 | resolved_data[key] = value |
| 284 | |
| 285 | if not resolved_data: |
| 286 | return ModuleResult(success=False, error="更新数据不能为空") |
| 287 | |
| 288 | # 构建UPDATE语句 |
| 289 | set_clause = ', '.join(f'`{k}` = %s' for k in resolved_data.keys()) |
| 290 | sql = f"UPDATE `{table}` SET {set_clause}" |
| 291 | if where: |
| 292 | sql += f" WHERE {where}" |
| 293 | |
| 294 | with conn.cursor() as cursor: |
| 295 | affected_rows = cursor.execute(sql, list(resolved_data.values())) |
| 296 | |
| 297 | # 保存影响行数到变量 |
| 298 | if variable_name: |
| 299 | context.variables[variable_name] = affected_rows |
| 300 | |
| 301 | return ModuleResult( |
| 302 | success=True, |
| 303 | message=f"更新成功,影响 {affected_rows} 行", |
| 304 | data={"affectedRows": affected_rows} |
| 305 | ) |
| 306 | except Exception as e: |
| 307 | return ModuleResult(success=False, error=f"更新失败: {str(e)}") |
| 308 | |
| 309 |
nothing calls this directly
no test coverage detected