Symfony2 +存储过程||如何获取结果?

时间:2014-02-01 04:26:56

标签: php mysql symfony stored-procedures symfony-2.4

我目前正在努力从Symfony 2.4.3中的nativquery中获取结果。简单来说,我正在构建一个JobQueue / MsgQueue系统,它只会添加/删除队列中的作业。过程将获取第一个作业,将其设置为活动状态,并且应该返回整个结果。确实存在问题 - 我无法取任何东西。

我用这个作为我的例子:How to execute Stored Procedures with Doctrine2 and MySQL

以下是我在ConsoleCommand Class中使用的代码:

protected function execute(InputInterface $input, OutputInterface $output)
{
    ## start
    $output->writeln('<comment>Starting JobQueue Ping process</comment>');

    // set doctrine
    $em = $this->getContainer()->get('doctrine')->getManager();

    $rsm = new ResultSetMapping;
    $result = $em->createNativeQuery(
        'CALL JobQueueGetJob (' .
        ':jobTypeCode' .
        ')', $rsm
    );

    $result->setParameters(array('jobTypeCode' => 1));
    $result->execute();
    $em->flush();

    if ($input->getOption('verbose')) {
        $output->writeln(var_dump($result->getResult()));
    }
}

您可以在此处找到程序代码和结果:
代码

PROCEDURE `JobQueueGetJob`(IN `jobType` TINYINT(2))
BEGIN
DECLARE jId int(11);
  SELECT `msgId` into jId FROM `jobqueue` WHERE `MsgTypeCode` = jobType AND `jState` = 'N' LIMIT 1;
  IF jId IS NOT NULL THEN
    UPDATE `jobqueue` SET `jState` = 'A' WHERE `msgId` = jId;
    SELECT * FROM `jobqueue` WHERE `msgId` = jId;
  END IF;
END

结果通过phpMyAdmin

Your SQL query has been executed successfully
0 rows affected by the last statement inside the procedure
SET @p0 =  '1';

CALL `JobQueueGetJob` (
@p0
);

正如文本所示,它将不会返回结果,但是程序中的最后一个语句应该是Query本身。


解决方案(不是最好的)
命令:

// set doctrine
$em = $this->getContainer()->get('doctrine')->getManager()->getConnection();

// prepare statement
$sth = $em->prepare("CALL JobQueueGetJob(1)");

// execute and fetch
$sth->execute();
$result = $sth->fetch();

// DEBUG
if ($input->getOption('verbose')) {
    $output->writeln(var_dump($result));
}

输出

array(5) {
  'msgId' =>
  string(3) "122"
  'msgTypeCode' =>
  string(1) "1"
  'jobCode' =>
  string(22) "http://mail.google.com"
  'jstate' =>
  string(1) "A"
  'created_at' =>
  string(19) "2014-02-01 03:58:42"
}

1 个答案:

答案 0 :(得分:5)

<强>解
以下是我最终找到的解决方案。它不是最好的,因为没有映射,但在我的情况下,没有必要 进一步:我需要更改为getConnection以获取PDO_MySQL并进一步更改为preparefetch()函数。 vardump显示现在是合适的结果。

// set doctrine
$em = $this->getContainer()->get('doctrine')->getManager()->getConnection();

// prepare statement
$sth = $em->prepare("CALL JobQueueGetJob(1)");

// execute and fetch
$sth->execute();
$result = $sth->fetch();

// DEBUG
if ($input->getOption('verbose')) {
    $output->writeln(var_dump($result));
}

输出

array(5) {
  'msgId' =>
  string(3) "122"
  'msgTypeCode' =>
  string(1) "1"
  'jobCode' =>
  string(22) "http://mail.google.com"
  'jstate' =>
  string(1) "A"
  'created_at' =>
  string(19) "2014-02-01 03:58:42"
}
相关问题