setName('tools:db:query') ->setDescription('执行 SQL 查询语句(SELECT)并显示结果') ->addArgument('sql', null, 'SQL 查询语句') ->addOption('limit', null, Option::VALUE_OPTIONAL, '限制显示行数') ->addOption('connection', null, Option::VALUE_OPTIONAL, '指定数据库连接配置') ->addOption('help', 'h', Option::VALUE_NONE, '显示帮助信息'); } protected function execute($input, $output) { if ($input->getOption('help')) { $service = new DbService(); $service->showHelp('tools:db:query', $output); return; } $service = new DbService(); if (!$service->checkDebugMode($output)) { return; } $connection = $service->getDbConnection($input); $service->setConnection($connection); $sql = $input->getArgument('sql'); if (empty($sql)) { $output->error('请提供 SQL 查询语句'); return; } $limit = $input->getOption('limit'); if (!preg_match('/^\s*SELECT\s+/i', $sql)) { $output->error('仅支持 SELECT 语句,请使用 tools:db:execute 执行其他 SQL 语句'); return; } try { $startTime = microtime(true); $query = Db::connect($connection)->query($sql); $endTime = microtime(true); $executionTime = round(($endTime - $startTime) * 1000, 2); if (!is_array($query)) { $query = []; } if ($limit && is_numeric($limit)) { $query = array_slice($query, 0, (int)$limit); } $output->newLine(); $service->formatTableOutput($query, $output); $output->newLine(); $output->info('查询成功'); $output->writeln('影响行数:' . count($query)); $output->writeln('执行时间:' . $executionTime . 'ms'); $output->newLine(); } catch (\Exception $e) { $output->error('查询失败:' . $e->getMessage()); return; } } }