/** * Return an array of error information about the last * performed operation. * * @param bool Value determines if the errorInfo should * be performed on the database handle or * the statement handle. * @return array */ public function error($connection = TRUE) { if ($connection) { return $this->connection->errorInfo(); } return $this->statement->errorInfo(); }
/** * Handles PDO error by either printing it to the screen with other useful information (dev mode) * or logging the error * * @param PDOStatement $stmt */ protected function handlePdoError(\PDOStatement $stmt) { if ($this->mode == 'dev') { print_r($stmt->errorInfo()); } else { if ($this->mode == 'prod') { error_log(implode(' - ', $stmt->errorInfo())); } } }
/** * Executes a query using current database connection * * @param $query * @return Tx_PtExtlist_Domain_DataBackend_DataSource_MySqlDataSource * @throws Exception */ public function executeQuery($query) { try { /* @var $statement PDOStatement */ $this->startTimeMeasure(); $this->statement = $this->connection->prepare($query); $this->statement->execute(); $this->stopTimeMeasure(); } catch (Exception $e) { throw new Exception('Error while trying to execute query on database! SQL-Statement: ' . $query . ' - Error message from PDO: ' . $e->getMessage() . '. Further information from PDO_errorInfo: ' . $this->statement->errorInfo(), 1280322659); } return $this; }
/** * Run a query against a database. Get a result * @param string $query The SQL to run against the database * @param array $args An associative array of query parameters * @return bool|\PDOStatement False if query fails, results in this database's fetch_class if successful * @throws \Exception */ public function query($query, $args = array()) { if (!empty($this->pdo_statement)) { $this->pdo_statement->closeCursor(); } if ($this->pdo_statement = $this->prepare($query, array(PDO::ATTR_EMULATE_PREPARES => true))) { $this->pdo_statement->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, $this->fetch_class, [$this]); if (!$this->pdo_statement->execute($args)) { throw new \Exception($this->pdo_statement->errorInfo()); } return true; } else { throw new \Exception($this->errorInfo()); } }
/** * {@inheritDoc} * @see \vxPHP\Database\DatabaseInterface::deleteRecord() * * @throws \PDOException */ public function deleteRecord($tableName, $keyValue) { if (!is_array($keyValue)) { if (!array_key_exists($tableName, $this->tableStructureCache) || empty($this->tableStructureCache[$tableName])) { $this->fillTableStructureCache($tableName); } if (!array_key_exists($tableName, $this->tableStructureCache)) { throw new \PDOException(sprintf("Table '%s' not found.", $tableName)); } if (count($this->tableStructureCache[$tableName]['_primaryKeyColumns']) === 1) { $this->statement = $this->connection->prepare(sprintf("\n\t\t\t\t\t\t\tDELETE FROM\n\t\t\t\t\t\t\t\t%s\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t%s%s%s = ?\n\t\t\t\t\t\t", $tableName, self::QUOTE_CHAR, $this->tableStructureCache[$tableName]['_primaryKeyColumns'][0], self::QUOTE_CHAR)); $this->statement->execute((array) $keyValue); return $this->statement->rowCount(); } else { throw new \PDOException(sprintf("Table '%s' has more than one or no primary key column.", $tableName)); } } else { $fieldNames = []; foreach (array_keys($keyValue) as $fieldName) { $fieldNames[] = self::QUOTE_CHAR . $fieldName . self::QUOTE_CHAR . ' = ?'; } $this->statement = $this->connection->prepare(sprintf("\n\t\t\t\t\t\tDELETE FROM\n\t\t\t\t\t\t\t%s\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t%s\n\t\t\t\t\t", $tableName, implode(' AND ', $fieldNames))); if ($this->statement->execute(array_values($keyValue))) { return $this->statement->rowCount(); } throw new \PDOException(vsprintf('ERROR: %s, %s, %s', $this->statement->errorInfo())); } }
/** * Executes the request against a PDO object * * @return bool|Atomik_Db_Query_Result False if fail or the Atomik_Db_Query_Result object */ public function execute($reCache = false, Atomik_Db_Query_Result $resultObject = null) { if ($this->_instance === null) { require_once 'Atomik/Db/Query/Exception.php'; throw new Atomik_Db_Query_Exception('An Atomik_Db_Instance must be attached to the queyr to execute it'); } if (($resultObject === null || !$reCache) && $this->_cachedResult !== null) { return $this->_cachedResult; } if ($this->_statement === null) { // prepare the query only if the statement is not already prepared $this->_statement = $this->_pdo->prepare($this->toSql()); } $this->_lastError = false; if (!$this->_statement->execute($this->getParams())) { $this->_lastError = $this->_statement->errorInfo(); return false; } if ($resultObject === null) { $resultObject = new Atomik_Db_Query_Result($this); if ($this->_cacheable) { $this->_cachedResult = $resultObject; } } $resultObject->reset($this->_statement); return $resultObject; }
static function check_errors(PDOStatement $query) { $status = $query->errorInfo(); if ($status[0] != 0) { throw new InternalException($status[2]); } }
/** * PDOSatement执行prepare,在失败时会重试 * @param array $params 执行参数 * @param array $retryTimes 重试次数 * @return 成功时返回 TRUE , 或者在失败时返回 FALSE */ public function execute($params = array(), $retryTimes = 3) { $res = $this->pdoStatement->execute($params); if ($res !== FALSE) { return $res; } // 这么写的原因是:如果第一次成功,就不需要while循环结构了,比起全部写在while循环里,效率要高很多 // 如果第一次查询失败,则重试3次 $retry = 0; while ($retry < $retryTimes) { $errInfo = $this->pdoStatement->errorInfo(); if (is_array($errInfo) && $errInfo[0] == 'HY000' && $errInfo[1] == '2006') { // Mysql gone away if (!$this->reconnPdo()) { return FALSE; } } else { // 甩出错误 // throw new Error return FALSE; // 其他错误不重试,返回失败 } $this->pdoStatement = $this->pdo->prepare($this->sql); $res = $this->pdoStatement->execute($params); if ($res !== FALSE) { return $res; } $retry++; } return FALSE; // 最终返回FALSE }
public function execute($input_parameters = NULL) { if (APF::get_instance()->is_debug_enabled()) { APF::get_instance()->debug(__CLASS__ . '[' . $this->pdo->config['dsn'] . '|' . $this->pdo->get_name() . ']' . "->execute: " . $this->queryString); } $logger = APF::get_instance()->get_logger(); $logger->debug(__CLASS__, '[' . $this->pdo->get_name() . ']->execute: ', $this->queryString); APF::get_instance()->pf_benchmark_inc_begin('dbtime'); $start = microtime(true); $ret = parent::execute($input_parameters); $end = microtime(true); APF::get_instance()->pf_benchmark_inc_end('dbtime'); //add by hexin for record SQL execute time APF::get_instance()->pf_benchmark("sql_time", array($this->i => $end - $start)); // 按照惯用格式记录sql执行时间和占用内存 // added by htlv $tmp_time = $end - $start; $tmp_mem = memory_get_usage(); apf_require_class('APF_Performance'); APF::get_instance()->pf_benchmark("sql_time_af", array($this->i => array('sql' => $this->_sql, APF_Performance::MESSAGE_TIME => $tmp_time, APF_Performance::MESSAGE_MEMORY => $tmp_mem))); if (!$ret) { $error_info = parent::errorInfo(); /** * remove duplicated error log $logger->error(__CLASS__, '['. $this->pdo->get_name() .']->execute: ', $this->queryString); $_error_info = preg_replace("#[\r\n \t]+#",' ',print_r($error_info,true)); $logger->error(__CLASS__, '['. $this->pdo->get_name() .']->execute: ', $_error_info); */ if (parent::errorCode() !== '00000') { throw new APF_Exception_SqlException($this->pdo->get_name() . ' | ' . $this->pdo->config['dsn'] . ' | ' . $this->queryString . ' | ' . join(' | ', $error_info), parent::errorCode()); } } return $ret; }
public function errorInfo() { if ($this->_statement instanceof \PDOStatement) { return $this->_statement->errorInfo(); } return null; }
public function execute($input_parameters = NULL) { if (APF::get_instance()->is_debug_enabled()) { APF::get_instance()->debug(__CLASS__ . '[' . $this->pdo->config['dsn'] . '|' . $this->pdo->get_name() . ']' . "->execute: " . $this->queryString); } $logger = APF::get_instance()->get_logger(); $logger->debug(__CLASS__, '[' . $this->pdo->get_name() . ']->execute: ', $this->queryString); APF::get_instance()->pf_benchmark_inc_begin('dbtime'); $start = microtime(true); $ret = parent::execute($input_parameters); $end = microtime(true); APF::get_instance()->pf_benchmark_inc_end('dbtime'); //add by hexin for record SQL execute time APF::get_instance()->pf_benchmark("sql_time", array($this->i => $end - $start)); if (!$ret) { $error_info = parent::errorInfo(); $logger->error(__CLASS__, '[' . $this->pdo->get_name() . ']->execute: ', $this->queryString); $_error_info = preg_replace("#[\r\n \t]+#", ' ', print_r($error_info, true)); $logger->error(__CLASS__, '[' . $this->pdo->get_name() . ']->execute: ', $_error_info); if (parent::errorCode() !== '00000') { trigger_error($this->queryString . ' | ' . join(' | ', $error_info), E_USER_ERROR); } } return $ret; }
/** * Return an array of error information about the last * performed operation. * * @param bool Value determines if the errorInfo should * be performed on the database handle or * the statement handle. * @return array */ public function error($connection = true) { if ($connection) { return array("error" => $this->connection->errorInfo()); } return array("error" => $this->statement->errorInfo()); }
public function __construct($message, PDOStatement $statement) { $infos = array(); foreach ($statement->errorInfo() as $key => $info) { $infos[] = $key . ': ' . $info; } parent::__construct($message . '. (ERRNO ' . $statement->errorCode() . ') ' . implode('<br />', $infos)); }
/** * Returns the description of the last error. * * @return string */ public function getErrorDesc() { if ($this->pdoStatement !== null) { $errorInfoArray = $this->pdoStatement->errorInfo(); if (isset($errorInfoArray[2])) return $errorInfoArray[2]; } return ''; }
/** * Tries to execute a statement, throw an explicit exception on failure */ protected function execute(\PDOStatement $query, array $variables = array()) { if (!$query->execute($variables)) { $errors = $query->errorInfo(); throw new ModelException($errors[2]); } return $query; }
/** * Execute a SQL statement. * * @param string $query the SQL statement * @param array $args values for the bound parameters * @return boolean true on success, false on failure */ public function query($query, $args = array()) { if ($this->pdo_statement != null) { $this->pdo_statement->closeCursor(); } // Allow plugins to modify the query $query = Plugins::filter('query', $query, $args); // Translate the query for the database engine $query = $this->sql_t($query, $args); // Replace braced table names in the query with their prefixed counterparts $query = self::filter_tables($query); // Allow plugins to modify the query after it has been processed $query = Plugins::filter('query_postprocess', $query, $args); if ($this->pdo_statement = $this->pdo->prepare($query)) { if ($this->fetch_mode == \PDO::FETCH_CLASS) { /* Try to get the result class autoloaded. */ if (!class_exists($this->fetch_class_name, true)) { $class_name = $this->fetch_class_name; // @todo This is a GIANT namespace kludge, replacing Model class names with no namespace that don't exist with a default prefixed class if (strpos($class_name, '\\') == false) { $class_name = '\\Habari\\' . $class_name; $this->fetch_class_name = $class_name; if (!class_exists($this->fetch_class_name, true)) { throw new \Exception('The model class that was specified for data retreival could not be loaded.'); } } } /* Ensure that the class is actually available now, otherwise segfault happens (if we haven't died earlier anyway). */ if (class_exists($this->fetch_class_name)) { $this->pdo_statement->setFetchMode(\PDO::FETCH_CLASS, $this->fetch_class_name, array()); } else { /* Die gracefully before the segfault occurs */ echo '<br><br>' . _t('Attempt to fetch in class mode with a non-included class') . '<br><br>'; return false; } } else { $this->pdo_statement->setFetchMode($this->fetch_mode); } /* If we are profiling, then time the query */ if ($this->keep_profile) { $profile = new QueryProfile($query); $profile->params = $args; $profile->start(); } if (!$this->pdo_statement->execute($args)) { $this->add_error(array('query' => $query, 'error' => $this->pdo_statement->errorInfo())); return false; } if ($this->keep_profile) { $profile->stop(); $this->profiles[] = $profile; } return true; } else { $this->add_error(array('query' => $query, 'error' => $this->pdo->errorInfo())); return false; } }
public static function castPdoStatement(\PDOStatement $c, array $a, Stub $stub, $isNested) { $m = "~"; $a[$m . 'errorInfo'] = $c->errorInfo(); if (!isset($a[$m . 'errorInfo'][1], $a[$m . 'errorInfo'][2])) { unset($a[$m . 'errorInfo']); } return $a; }
/** * @return string */ public function getErrorDescription() { if ($this->pdoStatement !== null) { if (isset($this->pdoStatement->errorInfo()[2])) { return $this->pdoStatement->errorInfo()[2]; } } return ''; }
/** * * @param $objPDO - PDO object to get error information from * * @return (string) a flatten error info from the query object * * build and return a flatten error-info * from the driver specific error message * **/ private function flattenQueryErrorInfo(\PDOStatement $objPDO) { $arrErrorInfo = $objPDO->errorInfo(); $strMessage = ''; if (!empty($arrErrorInfo) && !empty($arrErrorInfo[0]) && '00000' !== $arrErrorInfo[0]) { $strMessage = "\nError-Code: {$arrErrorInfo[0]}\nError-Message: {$arrErrorInfo[2]}\n"; } return $strMessage; }
public static function castPdoStatement(\PDOStatement $c, array $a, Stub $stub, $isNested) { $prefix = Caster::PREFIX_VIRTUAL; $a[$prefix . 'errorInfo'] = $c->errorInfo(); if (!isset($a[$prefix . 'errorInfo'][1], $a[$prefix . 'errorInfo'][2])) { unset($a[$prefix . 'errorInfo']); } return $a; }
private function executeQuery(\PDOStatement $s, $params = array()) { $r = $s->execute($params); if (!$s) { echo $s->queryString; throw new \Exception($s->errorInfo()); } return $r; }
/** * Retrieves an array of error information, if any, associated with the * last operation on the statement handle. * * @return array * @throws Zend_Db_Statement_Exception */ public function errorInfo() { try { return $this->_stmt->errorInfo(); } catch (PDOException $e) { require_once 'Zend/Db/Statement/Exception.php'; throw new Zend_Db_Statement_Exception($e->getMessage()); } }
/** * Performs a query, then returns a resultset * * @param string $action[optional] The crud action performed (select, insert, update, delete, create, alter) * * @return Resultset */ public function performQuery($action = '') { try { $values = $this->getCriteria() instanceof Criteria ? $this->getCriteria()->getValues() : array(); \TBGLogging::log('executing PDO query (' . Core::getSQLCount() . ') - ' . ($this->getCriteria() instanceof Criteria ? $this->getCriteria()->action : 'unknown'), 'B2DB'); $time = explode(' ', microtime()); $pretime = $time[1] + $time[0]; $res = $this->statement->execute($values); if (!$res) { $error = $this->statement->errorInfo(); if (Core::isDebugMode()) { $time = explode(' ', microtime()); $posttime = $time[1] + $time[0]; Core::sqlHit($this->printSQL(), implode(', ', $values), $posttime - $pretime); } throw new Exception($error[2], $this->printSQL()); } if (Core::isDebugMode()) { \TBGLogging::log('done', 'B2DB'); } if ($this->getCriteria() instanceof Criteria && $this->getCriteria()->action == 'insert') { if (Core::getDBtype() == 'mysql') { $this->insert_id = Core::getDBLink()->lastInsertId(); } elseif (Core::getDBtype() == 'pgsql') { \TBGLogging::log('sequence: ' . Core::getTablePrefix() . $this->getCriteria()->getTable()->getB2DBName() . '_id_seq', 'b2db'); $this->insert_id = Core::getDBLink()->lastInsertId(Core::getTablePrefix() . $this->getCriteria()->getTable()->getB2DBName() . '_id_seq'); \TBGLogging::log('id is: ' . $this->insert_id, 'b2db'); } } $action = $this->getCriteria() instanceof Criteria ? $this->getCriteria()->action : ''; $retval = new Resultset($this); if (Core::isDebugMode()) { $time = explode(' ', microtime()); $posttime = $time[1] + $time[0]; Core::sqlHit($this->printSQL(), implode(', ', $values), $posttime - $pretime); } if (!$this->getCriteria() || $this->getCriteria()->action != 'select') { $this->statement->closeCursor(); } return $retval; } catch (\Exception $e) { throw $e; } }
/** * Permet d'exécuter une requête. * * Aucun résultat n'est renvoyé par cette fonction. Elle doit être utilisé pour effectuer * des insertions, des updates... Elle est de même utilisée par les * autres fonction de la classe comme queryRow() et queryTab(). * * @param string $query chaine SQL * @param mixed $param variables bind de type array(":bind"=>"value") * @return void */ public function query($query, $param = array()) { global $sysNbQuery; // execution de la requête $this->query = (isset($_SERVER['HOSTNAME']) ? '/*SIG'.$_SERVER['HOSTNAME'].'SIG*/ ' : '').$query; $this->param = $param; $this->errorParams = array(); $this->errorParams['Request'] = $query; $this->errorParams['Bind'] = $param; $this->id->setAttribute(PDO::ATTR_AUTOCOMMIT, $this->getCommitMode()); $this->id->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); $sysNbQuery = (!isset($sysNbQuery) || $sysNbQuery<=0) ? 1 : $sysNbQuery+1; // Prepare de la requête $queryMD5 = md5($query); if(!isset($this->aPrepare[$queryMD5])) { $this->lPrepare = $this->id->prepare($this->query); $this->aPrepare[$queryMD5] = $this->lPrepare; } else { $this->lPrepare = $this->aPrepare[$queryMD5]; } if ($this->lPrepare!==false) { // Bind des paramètres if($param) { foreach($param as $key => $val) { if (strpos($query, $key) !== false) { if($param[$key]===null) $this->lPrepare->bindParam(trim($key), $param[$key], PDO::PARAM_NULL); else $this->lPrepare->bindParam(trim($key), $param[$key]); } } } // Execution de la requête $rs = $this->lPrepare->execute(); if ($this->lPrepare->errorCode() != PDO::ERR_NONE) { $this->errorParams['errorInfo'] = $this->lPrepare->errorInfo(); //echo'<xmp>Erreur execute() de PDO : '.$this->errorParams['errorInfo'][2];print_r($query);echo'</xmp>'; //Génération d'une DataBaseException //throw new DataBaseException("Erreur execute() de PDO",$error[2],$this->errorParams); } return $rs; }else{ $this->errorParams['errorInfo'] = $this->lPrepare->errorInfo(); //echo'<xmp>Erreur prepare() de PDO : '.$this->errorParams['errorInfo'][2];print_r($query);echo'</xmp>'; //DatabaseManager::log($this, true); //throw new DataBaseException("Erreur prepare() de PDO",$this->id->errorInfo(),$this->errorParams); } return false; }
/** * @param PDOStatement|boolean $sth * @param mixed $result * @return boolean TRUE if $result indicates failure, FALSE otherwise */ private function isFailure($sth, $result) { if ($result === false) { $error = $sth->errorInfo(); $this->lastError = 'DB ERROR: [' . $sth->errorCode() . '] ' . $error[2]; error_log($this->lastError); return true; } return false; }
/** * Print error, if a Database error occurred. * * @param mixed $rvalue: The return value of PDOStatement->execute() function. * @param PDO $db * @return boolean */ public static function dbStmtAssert($rvalue, PDOStatement $stmt) { if ($rvalue === false) { $info = $stmt->errorInfo(); $e = new Exception(); self::log("Database statement created error:\nCode: " . $info[0] . " DB-Code: " . $info[1] . " Message: " . $info[2] . "\n\n" . $e, "warning", 'db'); return false; } return true; }
/** * Permet d'exécuter une requête. * * Aucun résultat n'est renvoyé par cette fonction. Elle doit être utilisé pour effectuer * des insertions, des updates... Elle est de même utilisée par les * autres fonction de la classe comme queryRow() et queryTab(). * * @param string $query chaine SQL * @param mixed $param variables bind de type array(":bind"=>"value") * @return void */ public function query($query, $param = array()) { global $sysNbQuery; // execution de la requête $this->query = (isset($_SERVER['HOSTNAME']) ? '/*SIG' . $_SERVER['HOSTNAME'] . 'SIG*/ ' : '') . $query; $this->param = $param; $this->stmt = null; $this->id->setAttribute(PDO::ATTR_AUTOCOMMIT, $this->getCommitMode()); $this->id->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); $sysNbQuery = (!isset($sysNbQuery) || $sysNbQuery <= 0) ? 1 : $sysNbQuery + 1; try { // Prepare de la requête $this->stmt = $this->id->prepare($this->query); if ($this->stmt !== false) { // Bind des paramètres if (!empty($param)) { foreach ($param as $key => $val) { // ATTENTION, il faut $param[$key] et pas $val car c'est un passage par référence // les valeurs seront évaluées à l'exécution du statement if (strpos($query, $key) !== false) { if ($param[$key] === null) { $this->stmt->bindParam(trim($key), $param[$key], PDO::PARAM_NULL); } else { $this->stmt->bindParam(trim($key), $param[$key]); } } // sinon rien, clés en trop autorisées } } // Execution de la requête $this->data = $this->stmt->execute(); if ($this->stmt->errorCode() != PDO::ERR_NONE) { //Génération d'une DataBaseException $error = $this->stmt->errorInfo(); throw new DataBaseException($error[2], $error[0]); } return $this->data; } else { //Génération d'une DataBaseException $error = $this->stmt->errorInfo(); throw new DataBaseException($error[2], $error[0]); } } catch (PDOException $e) { // Transformation de PDOException en DataBaseException throw new DataBaseException($e->getMessage(), $e->getCode()); } }
public function getLastError() { if ($this->hasError($this->lastStatement)) { $error = $this->lastStatement->errorInfo(); } elseif ($this->hasError($this->pdoConnection)) { $error = $this->pdoConnection->errorInfo(); } if (isset($error)) { return sprintf("%s-%s: %s", $error[0], $error[1], $error[2]); } }
/** * Generate PDO error * * @param string $sql * @param \PDOStatement $statement * @return \PDOException */ protected function error($sql, \PDOStatement $statement = null) { $error = $this->pdo->errorInfo(); if (!$error[1] and $statement) { $error = $statement->errorInfo(); $statement->closeCursor(); unset($statement); } $code = is_int($error[0]) ? $error[0] : null; return new \PDOException('[' . $error[0] . '] ' . $error[2] . ', in query (' . $sql . ')', $code); }
public function getErrorMessage() { if ($this->pdoStatement) { $err = $this->pdoStatement->errorInfo(); } elseif ($this->pdo) { $err = $this->pdo->errorInfo(); } else { return null; } return empty($err[2]) ? '' : $err[2]; }