/** * @brief 设置数据库读写分离并且执行SQL语句 * @param string $sql 要执行的SQL语句 * @return int or bool SQL语句执行的结果 */ public function query($sql) { //取得SQL类型 self::$sqlType = $this->getSqlType($sql); //读方式 if (self::$sqlType == 'select' || self::$sqlType == 'show') { if (self::$rTarget == NULL || !is_resource(self::$rTarget)) { //多数据库支持并且读写分离 if (isset(IWeb::$app->config['DB']['read'])) { //获取ip地址 $ip = IClient::getIP(); $this->connect(IHash::hash(IWeb::$app->config['DB']['read'], $ip)); } else { $this->connect(IWeb::$app->config['DB']); } self::$rTarget = $this->linkRes; } } else { if (self::$wTarget == NULL || !is_resource(self::$wTarget)) { //多数据库支持并且读写分离 if (isset(IWeb::$app->config['DB']['write'])) { $this->connect(IWeb::$app->config['DB']['write']); } else { $this->connect(IWeb::$app->config['DB']); } self::$wTarget = $this->linkRes; } } if (is_resource($this->linkRes)) { return $this->doSql($sql); } else { return false; } }
/** * @brief 设置数据库读写分离并且执行SQL语句 * @param string $sql 要执行的SQL语句 * @return int or bool SQL语句执行的结果 */ public function query($sql) { //取得SQL类型 self::$sqlType = $this->getSqlType($sql); //读方式 if (self::$sqlType == 'select' || self::$sqlType == 'show') { if (self::$rTarget == NULL) { //多数据库支持并且读写分离 if (isset(IWeb::$app->config['DB']['read'])) { //获取ip地址 $ip = IClient::getIP(); self::$rTarget = $this->connect(IHash::hash(IWeb::$app->config['DB']['read'], $ip)); } else { self::$rTarget = $this->connect(IWeb::$app->config['DB']); } } $this->switchLink("r"); $result = $this->doSql($sql); if ($result === false) { throw new IException("{$sql}\n -- " . $this->linkRes->error, 1000); return false; } return $result; } else { if (self::$wTarget == NULL) { //多数据库支持并且读写分离 if (isset(IWeb::$app->config['DB']['write'])) { self::$wTarget = $this->connect(IWeb::$app->config['DB']['write']); } else { self::$wTarget = $this->connect(IWeb::$app->config['DB']); } //写链接启用事务 $this->switchLink("w"); $this->autoCommit(); } $this->switchLink("w"); $result = $this->doSql($sql); if ($result === false) { $errorMsg = $this->linkRes->error; $this->rollback(); throw new IException("{$sql}\n -- " . $errorMsg, 1000); return false; } return $result; } }