/** * intizializes the database class and tries to estabilish database connections * * @return NULL */ function __construct() { global $cfg_value; // +++ main database connection try { $dsn = $cfg_value['server']['server_engine'] . ':host=' . $cfg_value['server']['server_host'] . ';port=' . $cfg_value['server']['server_port'] . ';dbname=' . $cfg_value['server']['server_db']; $this->connection_server = new PDO($dsn, $cfg_value['server']['server_username'], $cfg_value['server']['server_password']); $this->connection_server->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // +++ set names to UTF-8 try { $sql_names = "SET NAMES 'utf8';"; $query_names = $this->connection_server->exec($sql_names); $sql_character_set = "SET CHARACTER SET utf8;"; $query_character_set = $this->connection_server->exec($sql_character_set); } catch (PDOException $e) { } // --- set names to UTF-8 } catch (PDOException $e) { $this->connection_server = NULL; $this->error_server = $e->getMessage(); } // --- main database connection // register a shutdown function that closes the database connection register_shutdown_function(array($this, 'disconnect')); return; }
/** * intizializes the database class and tries to estabilish database connections * * @return NULL */ function __construct() { // +++ main database connection try { $dsn = CFG_DB_ENGINE . ':host=' . CFG_DB_HOST . ';port=' . CFG_DB_PORT . ';dbname=' . CFG_DB_DATABASE; $this->connection = new PDO($dsn, CFG_DB_USERNAME, CFG_DB_PASSWORD); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // +++ set names to UTF-8 try { $sql_names = "SET NAMES 'utf8';"; $query_names = $this->connection->exec($sql_names); $sql_character_set = "SET CHARACTER SET utf8;"; $query_character_set = $this->connection->exec($sql_character_set); } catch (PDOException $e) { } // --- set names to UTF-8 } catch (PDOException $e) { $this->connection = NULL; $this->error = $e->getMessage(); } // --- main database connection // register a shutdown function that closes the database connection register_shutdown_function(array($this, 'disconnect')); return; }
/** * Execute the deploy command * * @param object $ssh The SSH connection handle * @param string $project Name of the project * @param string $host Host type of project (Git/Local) * @param string $destination Location where project resides on the server * @param string $path Path to the project on the repository * @param string $commit Commit hash * @param string $branch Name of the branch * * @return string $output Output from git command */ function execute($ssh = null, $project = null, $host = null, $destination = null, $path = null, $commit = null, $branch = null) { if (!empty($destination)) { $output = "Performing deploy... \n"; // Check if path exists on server. $dircheck = $ssh->exec("[ -d '" . $destination . "' ] && echo 'found'"); if (strpos($dircheck, 'found') === false) { // Create project on server if not found $command = "mkdir -p " . $destination . "; cd " . $destination . "; "; if ($host == 'Github') { $command .= "git clone git://github.com/" . Configure::read('Ballista.githubAccount') . "/" . $project . " ./"; } elseif (Configure::read('Ballista.gitoliteProtocol')) { $command .= "git clone " . Configure::read('Ballista.gitoliteProtocol') . ":" . $project . " ./"; } else { $command .= "git clone " . Configure::read('Ballista.accessProtocol') . $path . " ./"; } // Perform the command $output .= $ssh->exec($command); if ($branch != Configure::read('Ballista.master')) { // If branch is not master, then go into the project and checkout the branch from the repo $output .= $ssh->exec("cd " . $destination . "; git checkout -b " . $branch . " origin/" . $branch); } } else { // Path found, so project already exists. Just fetch and set to desired version. $output .= $ssh->exec("cd " . $destination . "; git fetch; git reset --hard " . $commit); } return $output; } else { return "Error: Undefined path or action. Cannot execute.\n"; } }
public function execute($sql) { //参数分析 if (!$sql) { return false; } $result = $this->db_link->exec($sql); return $result; }
/** * 执行SQL语句并返回影响的行数 * @param string $sql * @return int * @throws Exception */ public function exec($sql) { util_log::appLog()->info(__CLASS__ . '::' . __FUNCTION__ . "(): SQL: {$sql}"); $affectedRows = $this->db->exec($sql); //数据库错误抛出异常就好,暂时不重连 if ($affectedRows === false) { $errorInfo = $this->errorInfo(); $errorCode = $this->errorCode(); util_log::monitor()->error(array('MONITOR_KEY' => "database_failed", 'errorCode' => $errorCode, 'errorInfo' => $errorInfo, 'sql' => $sql)); throw new Exception($errorInfo, $errorCode); } return $affectedRows; }
/** * establishes a database connection using PDO */ private function __construct() { try { // connect to the database $this->db = new PDO('mysql:host=' . Config::get('db.host') . ';dbname=' . Config::get('db.name'), Config::get('db.user'), Config::get('db.pass')); $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create tables if they don't exist $query = $this->db->exec("CREATE TABLE IF NOT EXISTS users(\n id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,\n username VARCHAR(25) NOT NULL,\n password VARCHAR(255) NOT NULL\n )"); $query = $this->db->exec("CREATE TABLE IF NOT EXISTS articles(\n id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,\n title VARCHAR(100) NOT NULL,\n body TEXT NOT NULL,\n created TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n )"); } catch (PDOException $e) { display_error($e->getMessage()); } }
/** * Activates places to stay for course * * @param $key * * @return boolean */ function activate($key, $price) { $res = $this->db->query('SELECT id FROM kortkursus_x_indkvartering WHERE kursus_id = ' . $this->course->getId() . ' AND indkvartering_key = ' . $key); if (PEAR::isError($res)) { throw new Exception($res->getUserInfo()); } if (!$res->fetchRow()) { $this->db->exec('INSERT INTO kortkursus_x_indkvartering SET datetime = NOW(), kursus_id = ' . $this->course->getId() . ', indkvartering_key = ' . $key . ', price = "' . $price . '"'); } else { $this->db->exec('UPDATE kortkursus_x_indkvartering SET datetime = NOW(), kursus_id = ' . $this->course->getId() . ', indkvartering_key = ' . $key . ', price = "' . $price . '"'); } return true; }
/** * @return object PDO * Caso exista retorna a conexão com o banco, se não existir realiza a conexão antes de retorna-lá */ public static function getConnection() { if (is_null(self::$connection)) { try { $dsn = DB_DRIVER . ':host=' . DB_HOST . ';dbname=' . DB_NAME; self::$connection = new \PDO($dsn, DB_USER, DB_PASS); self::$connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); self::$connection->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ); self::$connection->exec('set names utf8'); } catch (\PDOException $e) { echo $e->getMessage(); } } return self::$connection; }
/** * Check If An action Is In Progress For The Selected Context * * @param String $context * @return bool * @access public */ public function checkOperation($context) { switch (@$context) { case 'makeRepo': if (!empty($this->repoPath)) { if (intval(trim($this->sshConnection->exec('cd ' . $this->repoPath . "; ls -a | grep -c '.cachelock*'"))) != 0) { // Operation In Progress : Game Repo Locked return TRUE; } return FALSE; } break; //------------------------------------------------------+ //------------------------------------------------------+ case 'installGame': case 'updateGame': if (!empty($this->gameServerPath)) { if (trim($this->sshConnection->exec('test -f ' . $this->gameServerPath . ".cacheuid && echo 'true' || echo 'false'")) == 'true') { return TRUE; } return FALSE; } break; } }
/** * Pass method to PDO object * * @param string $method PDO method name * @param array $args PDO method arguments * @return object PDO method results */ public function __call($method, $args) { if ('use' === strtolower($method)) { if (!empty($args[0]) && is_string($args[0])) { $this->conn->exec("USE `{$args[0]}`;"); return $this; } else { throw new \PDOException("Invalid Database name"); } } elseif (!method_exists($this->conn, $method)) { throw new \PDOException(sprintf("Call to undefined method '%s'", $method)); } $len = count($args); if (0 === $len) { return $this->conn->{$method}(); } elseif (1 === $len) { return $this->conn->{$method}($args[0]); } elseif (2 === $len) { return $this->conn->{$method}($args[0], $args[1]); } elseif (3 === $len) { return $this->conn->{$method}($args[0], $args[1], $args[2]); } elseif (4 === $len) { return $this->conn->{$method}($args[0], $args[1], $args[2], $args[3]); } elseif (5 === $len) { return $this->conn->{$method}($args[0], $args[1], $args[2], $args[3], $args[4]); } else { return call_user_func_array(array($this->conn, $method), $args); } }
/** * Garbage collector * * This function is responsible for garbage collection. It is responsible * for deleting old counter logs. * * @access public * @param int $lifetime Maximum lifetime of counter logs. * @return void * @throws HTTP_FloodControl_Exception if an error occured during garbage collection. */ public function gc($lifetime) { $quotedTblName = $this->_db->quoteIdentifier($this->_options['table']); $query = sprintf("DELETE FROM %s WHERE access < %d", $quotedTblName, time() - $lifetime); $result = $this->_db->exec($query); if (PEAR::isError($result)) { throw new HTTP_FloodControl_Exception($result->getMessage(), $result->getCode()); } if ($this->_options['autooptimize']) { switch ($this->_db->phptype) { case 'mysql': $query = sprintf("OPTIMIZE TABLE %s", $quotedTblName); break; case 'pgsql': $query = sprintf("VACUUM %s", $quotedTblName); break; default: $query = null; break; } if (!is_null($query)) { $result = $this->_db->exec($query); if (PEAR::isError($result)) { throw new HTTP_FloodControl_Exception($result->getMessage(), $result->getCode()); } } } }
/** * Wykonanie przygotowanego zapytania SQL. Nie są pobierane żadne dane. * Zwracany ilość zmienionych rekordów. * * @param String $sql - zapytanie sql'owe * @param Array $params (default: array()) - parametry zapytania * @param bool $throwException * * @throws MK_Db_Exception * @return integer */ protected function Execute($sql, array $params = array(), $throwException = true) { // Bez array_values wywala błąd - nie ma być kluczy w tablicy! $params = array_values($params); // Uruchomienie licznika uruchamiania zapytania SQL $timeStart = MK_DEBUG_FIREPHP ? microtime(true) : 0; // Jeżeli zostały podany parametry, to wykonujemy zapytanie przy pomocy prepare/execute // W przeciwnym wypadku uruchiamy zapytanie poprzez exec(), które umożliwia wykonanie wielu zapytań SQL if (count($params) > 0) { $pdoObj = $this->db->prepare($sql); if ($pdoObj->execute($params) === false && $throwException === true) { throw new MK_Db_Exception(MK_Db_PDO_Singleton::MESSAGE_ERROR_RESULTS); } $affectedRows = $pdoObj->rowCount(); } else { $results = $this->db->exec($sql); if ($results === false && $throwException === true) { throw new MK_Db_Exception(MK_Db_PDO_Singleton::MESSAGE_ERROR_RESULTS); } $affectedRows = $results; } // Zwrócenie szczegółowego komunikatu w konsoli FireBug-a if (MK_DEBUG_FIREPHP) { $this->fireBugSqlDump("DbExecute", $sql, $params, microtime(true) - $timeStart); } // Jeżeli jest włączone debugowanie, to SQL-e zapisywane są do pliku debug.log $this->debugToFile($sql, $params); // Ilość zmodyfikowanych wierszy return $affectedRows; }
/** * Initialize the driver. * * Validate configuration and perform all resource-intensive tasks needed to * make the driver active. * * @throws ILSException * @return void */ public function init() { if (empty($this->config)) { throw new ILSException('Configuration needs to be set.'); } //Connect to MySQL $this->db = new PDO('mysql:host=' . $this->config['Catalog']['host'] . ';port=' . $this->config['Catalog']['port'] . ';dbname=' . $this->config['Catalog']['database'], $this->config['Catalog']['username'], $this->config['Catalog']['password']); // Throw PDOExceptions if something goes wrong $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Return result set like mysql_fetch_assoc() $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); //character set utf8 $this->db->exec("SET NAMES utf8"); //Storing the base URL of ILS $this->ilsBaseUrl = $this->config['Catalog']['url']; //Boolean - use id prefixes like "KN31120" or not $this->idPrefix = $this->config['Catalog']['id_prefix']; //Boolean - indicates if library uses barcodes (true), or if barcodes are // generated automatically (false) $this->useBarcodes = $this->config['Catalog']['use_barcodes']; //set number prefix for library $this->prefix = $this->config['Catalog']['prefix']; //how long (in days) hide new items $this->hideNewItemsDays = 0; if (isset($this->config['Catalog']['hide_days'])) { $this->c = $this->config['Catalog']['hide_days']; } }
/** * Prepare query to the database * * This function checks if we have already opened a connection to * the database. If that's not the case, a new connection is opened. * After that the query is passed to the database. * * @access public * @param string Query string * @return mixed a MDB_result object or MDB_OK on success, a MDB * or PEAR error on failure */ function query($query) { $err = $this->_prepare(); if ($err !== true) { return $err; } return $this->db->exec($query); }
/** * Tests the STDERR handle. * * @since 0.1 * @return void * * @depends testStderrSetHandle */ public function testExecStderrHandle() { $tmpfile = tmpfile(); $this->bunsen->stderrSetHandle($tmpfile); $this->bunsen->exec('echo "hello world" >&2'); rewind($tmpfile); $this->assertEquals(stream_get_contents($tmpfile), 'hello world' . "\n"); fclose($tmpfile); }
/** * Prepare query to the database * * This function checks if we have already opened a connection to * the database. If that's not the case, a new connection is opened. * After that the query is passed to the database. * * @access public * @param string Query string * @return mixed a MDB_result object or MDB_OK on success, a MDB * or PEAR error on failure */ function query($query) { $this->log('Auth_Container_MDB2::query() called.', AUTH_LOG_DEBUG); $err = $this->_prepare(); if ($err !== true) { return $err; } return $this->db->exec($query); }
/** * Хук роутера * * Если мы находим в кеше или в базе занятый путь, вызываем Callback по нему * * @param object $Router */ public function hookRouterRun($Router, $success = FALSE) { $uri = $Router->getUri(); if ($route = route($uri, 'route')) { if ($callback = $route->decodeCallback($route->callback)) { $Router->exec($callback); return $success; } } }
/** * Execute a manipulation query to the database and return any the affected rows * * @param string $query SQL query string * @param array $params replace values in the query * @param int $level The severity level if error occurred * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure * @access public */ function query($sql, $params = array(), $error_level = JAWS_ERROR_ERROR) { $sql = $this->sqlParse($sql, $params); $result = $this->dbc->exec($sql); if (MDB2::isError($result)) { $GLOBALS['log']->Log($error_level, $result->getUserInfo(), 2); return new Jaws_Error($result->getMessage(), $result->getCode(), $error_level, 1); } return (string) $result; }
/** * destroy. * * Takes an ID parameter, deletes from the table where the unique ID * matches the ID parameter * * @param int $id a unique ID from the table * * @return bool should return true or false based on * whether it was deleted or not */ public static function destroy($fieldId) { self::connect(); $sqlQuery = 'DELETE FROM ' . self::getTableName(); $sqlQuery .= ' WHERE ' . self::getUniqueId() . ' = ' . $fieldId; try { return self::$connection->exec($sqlQuery) ? true : false; } catch (PDOException $e) { throw new PDOException($e->getMessage()); } }
public static function exec($query) { try { if (!self::$instance instanceof \PDO) { throw new \PDOException(self::$exception['no-instance']); } return self::$instance->exec($query); } catch (\PDOException $e) { self::stackTrace($e); } }
/** * Delete Key(s) * * @param string $key * @return integer */ public function del($key) { $keys = func_get_args(); $removed = 0; foreach ($keys as $key) { $sql = 'DELETE FROM storage WHERE `key`="' . $key . '"'; $this->connection->exec($sql); $removed++; } return $removed; }
/** * 执行查询 * @access public * @param string $sql sql指令 * @param string $type = 0:INSERT, UPDATE 以及DELETE $type = 1:主要针对 SELECT, SHOW 等指令 * @todo 是否重写异常的抛出 * @return mixed */ public function query($sql = '', $type = '0', $reconnect = 1) { $this->connect(); if (empty($this->link)) { return false; } try { $this->queryStr = $sql; //释放前次的查询结果 if (!empty($this->PDOStatement)) { $this->free(); } switch ($type) { case '0': //echo $sql; $result = @$this->link->exec($this->queryStr); // 有错误则抛出异常 if (false === $result) { return false; } else { $this->numRows = $result; if (strripos($this->queryStr, 'insert') !== false) { $this->lastInsertId = $this->link->lastInsertId(); } return $this->numRows; } break; case '1': $this->PDOStatement = $this->link->prepare($this->queryStr); //var_dump($this->link); if (empty($this->PDOStatement)) { //error_log(date('H:i:s').'-->'.$this->queryStr."\n",3,TMP_PATH.'/'.date('Y-m-d').'pdo_prepare_error.log'); return false; } $bol = @$this->PDOStatement->execute(); return $bol; break; } } catch (PDOException $e) { //var_dump( $e->errorInfo ); if ($e->errorInfo[0] = 'HY000' || isset($e->errorInfo[2]) && strpos($e->errorInfo[2], 'gone away') !== false || $e->errorInfo[0] == 70100 || $e->errorInfo[0] == 2006) { if ($reconnect) { if ($this->pdo_reconnect(3)) { return $this->query($sql, $type, $reconnect = 0); } } } else { throw new PDOException($e->getMessage(), 5002); return false; } } }
/** * 执行更新性的SQL语句 * @param string $sql 要执行的SQL指令。 * @return integer * @access public * @tutorial 返回受修改或删除 SQL语句影响的行数。如果没有受影响的行,则返回 0。失败返回false */ public function exec($sql = '') { if (empty($sql)) { throw new PDOException('要执行的SQL语句为空。', 3002); } $this->connect(); if (empty($this->link)) { throw new PDOException('无法连接数据库。', 3005); } $this->queryStr = $sql; $result = $this->link->exec($sql); return $result; }
/** /* Execute the sql. It's different with query(), which return the stmt object. But this not. * * @access public * @return int the modified or deleted records. */ public function exec() { if (!empty(dao::$errors)) { return new PDOStatement(); } // If any error, return an empty statement object to make sure the remain method to execute. $sql = $this->processSQL(); try { $this->reset(); return $this->dbh->exec($sql); } catch (PDOException $e) { $this->app->triggerError($e->getMessage() . "<p>The sql is: {$sql}</p>", __FILE__, __LINE__, $exit = true); } }
/** * Writes current values for the user back to the database. * * @return bool true on success or false on failure * * @access private */ function _updateUserData() { if (!array_key_exists('lastlogin', $this->tables['users']['fields'])) { return true; } $query = 'UPDATE ' . $this->prefix . $this->alias['users'] . ' SET ' . $this->alias['lastlogin'] . '=' . $this->dbc->quote(date('Y-m-d H:i:s', $this->currentLogin)) . ' WHERE ' . $this->alias['auth_user_id'] . '=' . $this->dbc->quote($this->propertyValues['auth_user_id']); $rows_affected = $this->dbc->exec($query); if ($rows_affected === false) { $error_info = $this->dbc->errorInfo(); $this->stack->push(LIVEUSER_ERROR, 'exception', array('reason' => $error_info[2], 'debug' => $query)); return false; } return true; }
/** * 执行SQL语句 * @param string $sql 要执行的sql语句 * @param array | boolean $param 当执行参数化查询时需要的参数 * @see PDO::exec() */ public function execute($sql, $param = null) { $this->queries++; if (empty($sql) && $this->debug) { debug_print_backtrace(); exit; } $this->lastSql[$this->lastSqlNameSpace] = $sql; $this->lastSqlParam[$this->lastSqlNameSpace] = $param; if (is_null($param)) { $this->rows = $this->pdo->exec($sql); if ($this->rows === false) { $this->errors = $this->pdo->errorInfo(); // if (in_array($this->errors[1], $this->logSqlcodes)) { // $this->errors['sql'] = $sql; // $this->errors['params'] = $param; // } $this->errors($this->errors); return false; } else { return true; } } else { $this->stmt = $this->pdo->prepare($sql); if (is_array($param)) { $paramList = array(); foreach ($param as $k => $v) { $paramList[$k] = $v; } $param = $paramList; $result = $this->stmt->execute($param); } else { $result = $this->stmt->execute(); } if (false === $result) { $this->errors = $this->stmt->errorInfo(); $this->errors['sql'] = $sql; $this->errors['params'] = $param; $this->rows = 0; } else { $this->errors = null; $this->rows = $this->stmt->rowCount(); } return $result; } }
/** * Execute the sql. It's different with query(), which return the stmt object. But this not. * * @param string $sql * @access public * @return int the modified or deleted records. */ public function exec($sql = '') { if (!empty(dao::$errors)) { return new PDOStatement(); } // If any error, return an empty statement object to make sure the remain method to execute. if ($sql) { $this->sqlobj->sql = $sql; } $sql = $this->processSQL(); try { $this->reset(); return $this->dbh->exec($sql); } catch (PDOException $e) { $this->sqlError($e); } }
/** * 执行查询 * @access public * @param string $sql sql指令 * @param string $type = 0:INSERT, UPDATE 以及DELETE $type = 1:主要针对 SELECT, SHOW 等指令 * @todo 是否重写异常的抛出 * @return mixed */ public function query($sql = '', $type = '0') { $this->connect(); if (empty($this->link)) { return false; } $this->queryStr = $sql; //释放前次的查询结果 if (!empty($this->PDOStatement)) { $this->free(); } switch ($type) { case '0': //echo $sql; $result = $this->link->exec($this->queryStr); // 有错误则抛出异常 if (false === $result) { //echo $this->queryStr."\n<br>"; //$errorInfo = $this->link->errorInfo(); //throw PDOException($errorInfo[1].$errorInfo[2]."\n<br>".$this->queryStr,$errorInfo[0]); //die; //error_log(date('H:i:s').'-->'.$this->queryStr."\n",3,TMP_PATH.'/'.date('Y-m-d').'pdo_exec_error.log'); return false; } else { $this->numRows = $result; if (strripos($this->queryStr, 'insert') !== false) { //@todo下面方法是否必须,当前项目不需要$this->lastInsertId $this->lastInsertId = $this->link->lastInsertId(); } return $this->numRows; } break; case '1': $this->PDOStatement = $this->link->prepare($this->queryStr); //var_dump($this->link); if (empty($this->PDOStatement)) { //error_log(date('H:i:s').'-->'.$this->queryStr."\n",3,TMP_PATH.'/'.date('Y-m-d').'pdo_prepare_error.log'); return false; } $bol = $this->PDOStatement->execute(); return $bol; break; } }
/** * Downloads a file from the SCP server. * * Returns a string containing the contents of $remote_file if $local_file is left undefined or a boolean false if * the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the * operation * * @param string $remote_file * @param string $local_file * @return mixed * @access public */ function get($remote_file, $local_file = false) { if (!isset($this->ssh)) { return false; } if (!$this->ssh->exec('scp -f ' . escapeshellarg($remote_file), false)) { // -f = from return false; } $this->_send(""); if (!preg_match('#(?<perms>[^ ]+) (?<size>\\d+) (?<name>.+)#', rtrim($this->_receive()), $info)) { return false; } $this->_send(""); $size = 0; if ($local_file !== false) { $fp = @fopen($local_file, 'wb'); if (!$fp) { return false; } } $content = ''; while ($size < $info['size']) { $data = $this->_receive(); // SCP usually seems to split stuff out into 16k chunks $size += strlen($data); if ($local_file === false) { $content .= $data; } else { fputs($fp, $data); } } $this->_close(); if ($local_file !== false) { fclose($fp); return true; } return $content; }
/** * 构造方法 * * 用于初始化运行环境,或对基本变量进行赋值 * * @access public * * @param array $params 数据库连接参数,如主机名,数据库用户名,密码等 * * @return boolean */ public function __construct($params = array()) { //参数分析 if (!$params['dsn']) { Controller::halt('database config params error!', 'Normal'); } $params += $this->_defaultConfig; //数据库连接 try { $flags = array(PDO::ATTR_PERSISTENT => $params['persistency'], PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); //实例化数据库连接 $this->_dbLink = new PDO($params['dsn'], $params['username'], $params['password'], $flags); } catch (PDOException $exception) { //当调试模式关闭时 if (DOIT_DEBUG === false) { //记录错误日志 Log::write("Database server connect error! Error Code:{$exception->getCode()} Error Message:{$exception->getMessage()}", 'Warning'); //提示错误信息 Controller::showMsg('数据库连接失败!'); } //抛出异常信息 throw new DoitException('Database connect error!<br/>' . $exception->getMessage(), $exception->getCode()); } //设置数据编码 $driverName = $this->_dbLink->getAttribute(PDO::ATTR_DRIVER_NAME); switch ($driverName) { case 'mysql': case 'pgsql': $this->_dbLink->exec("SET NAMES {$params['charset']}"); break; case 'sqlsrv': $this->_dbLink->setAttribute(PDO::SQLSRV_ATTR_ENCODING, $params['charset']); break; } return true; }