【问题标题】:Prepared statement inside or outside a try/cach?在 try/catch 内部或外部准备语句?
【发布时间】:2016-08-08 17:25:36
【问题描述】:

我怀疑准备好的语句应该在 try/catch 块内部还是外部。

(这是我的 User 类的示例方法)

我应该这样做吗?

public function getEmail( $id_user ) {
  $this->_sql = 'SELECT Email FROM '.TBL_USERS.' WHERE IdUser = :id_user';
  $stmt = $this->_db->prepare($this->_sql);
  try {
    $stmt->bindParam(':id_user', $id_user, PDO::PARAM_INT);
    $stmt->execute();
    $row = $stmt->fetchObject();
    if (is_object($row)) {
      return $row->Email;
    }
    return NULL;
  } catch (PDOException $e) {
    throw $e;
  }  
}

还是这个?

public function getEmail( $id_user ) {
  $this->_sql = 'SELECT Email FROM '.TBL_USERS.' WHERE IdUser = :id_user';
  try {
    $stmt = $this->_db->prepare($this->_sql);
    $stmt->bindParam(':id_user', $id_user, PDO::PARAM_INT);
    $stmt->execute();
    $row = $stmt->fetchObject();
    if (is_object($row)) {
      return $row->Email;
    }
    return NULL;
  } catch (PDOException $e) {
    throw $e;
  }
}

【问题讨论】:

  • 始终在try 中做好准备。 sql 语法错误可以/将会潜入。
  • 如果你不打算对异常做任何有意义的,那么就不要抓住它。像这样重新抛出异常只会使堆栈跟踪更难以阅读。

标签: php pdo try-catch prepared-statement


【解决方案1】:

prepare() 方法可能会引发 PDOException,因此您应该在 try 块中包含对 prepare 的调用。 但是,在这两个示例中,您只是重新抛出异常。除非你真的要在 catch 块内处理异常,否则效果是一样的。

【讨论】:

    猜你喜欢
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多