PDO不会因多个查询而抛出异常

时间:2016-10-18 19:15:51

标签: php sql-server pdo odbc pdo-odbc

如何在执行多个查询时让PDO抛出异常?

如果我自己运行错误的sql:

$execute($ddl_partial);
$execute($insert);

然后我得到了预期的错误:

  

PHP致命错误:未捕获PDOException:SQLSTATE [42S22]:找不到列:207 [Microsoft] [SQL Server的ODBC驱动程序13] [SQL Server]无效的列名称“其他”。 (SQLExecute [207] at /build/php7.0-41GaEn/php7.0-7.0.8/ext/pdo_odbc/odbc_stmt.c:260)

但是,如果我首先运行一些好的SQL并使用坏的跟进,那么它只是吞下错误并且一切正常。但之后查看数据库确认所有查询在错误语句后失败。

$execute($ddl_full);
$execute($insert);

$execute($drop);
$execute($ddl_partial);
$execute($insert);

我正在使用while ($statement->nextRowset())重复所有返回的行集demonstrated in this answer,但它只打印了8次:

array(4) {
  [0] =>
  string(5) "00000"
  [1] =>
  int(0)
  [2] =>
  string(24) " ((null)[0] at (null):0)"
  [3] =>
  string(0) ""
}

加起来:

  • 1 - 首先放弃
  • 1 - 完整ddl
  • 3 - 首次插入
  • 1秒钟下降
  • 1 - 部分ddl
  • 1 - 来自插入的第一个语句(第二个是错误的,所以第三个从不执行)

为什么我没有从错误的声明中收到错误消息?

<?php

$hostname = 'microsoftsql.example.com';
$database = 'mydb';
$username = 'user';
$password = 'P@55w0rd';
// https://www.microsoft.com/en-us/download/details.aspx?id=50419
$driver   = 'ODBC Driver 13 for SQL Server';

$pdo = new PDO("odbc:Driver=$driver;
    Server=$hostname;
    Database=$database",
    $username,
    $password
);
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false  );

$drop = "DROP TABLE testerino;";

$ddl_full = "
    CREATE TABLE testerino (
        value VARCHAR(10),
        other VARCHAR(10)
    );
";

$ddl_partial = "
    CREATE TABLE testerino (
        value VARCHAR(10)
    );
";

$insert = "
    INSERT INTO testerino (value)
    VALUES ('first');

    INSERT INTO testerino (value, other)
    VALUES ('second', 'another');

    INSERT INTO testerino (value)
    VALUES ('third');
";

$execute = function (String $sql) use ($pdo) {
    $pdo->beginTransaction();
    try {
        $statement = $pdo->prepare($sql);
        $statement->execute();
        do {
            /* https://bugs.php.net/bug.php?id=61613 */
            var_dump($statement->errorInfo());
        } while ($statement->nextRowset());
        $pdo->commit();
    } catch (PDOException $e) {
        $pdo->rollBack();
        throw $e;
    } finally {
        $statement->closeCursor();
    }
};

$execute($drop); // not needed first time
$execute($ddl_full);
$execute($insert);

$execute($drop);
$execute($ddl_partial);
$execute($insert);

这对我来说是个大问题,因为永远不会抛出异常,因此事务不会回滚,最终只会插入1/3记录。我需要全部或全部。

我正在运行Ubuntu Linux 16.04.1,PHP 7.0.8-0ubuntu0.16.04.3(cli)(NTS)连接到Microsoft SQL Server 2012(SP3)(KB3072779) - 11.0.6020.0(X64)使用Microsoft® ODBC Driver 13 (Preview) for SQL Server®

0 个答案:

没有答案