PDO $ stmt-> fetch()会发生哪些错误?

时间:2015-04-08 21:25:24

标签: php pdo try-catch

我在php.net找到了此示例代码:

function readDataForwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET';
  try {
    $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    }
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}

我的经验是,只有当$dbh->prepare失败(sql server已经消失,sql语句错误等)并且我的代码可能包含在while()内部时,才会发生异常。额外的SQL查询(使用嵌套的try/catch块)我想通过移动catch (...) {...}部分来了解是否以及错过了什么错误,从而产生更清晰的代码:

function readDataForwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET';
  try {
    $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt->execute();
  }
  catch (PDOException $e) {
    $stmt = new AnObj();
    $stmt->fetch = function() { return false; };
    print $e->getMessage();
  }
  while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
    $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
    print $data;
  }
  $stmt = null;
}

那么$stmt->fetch()可能导致哪些异常我不想错过?

更新:AnObj已添加。

0 个答案:

没有答案