执行查询 返回数据集
@access public
@param string      $sql    sql指令
@param array       $bind   参数绑定
@param boolean     $master 是否在主服务器读操作
@param bool|string $class  指定返回的数据集对象
@return mixed
@throws BindParamException
@throws PDOException
540734
public function query($sql, $bind = [], $master = false, $class = false)
    {
        return $this->connection->query($sql, $bind, $master, $class);
    }
457332
public function statement($sql, $bindings = array())
    {
        $start = microtime(true);
        $pdoStatement = $this->pdo->prepare($sql);
        foreach ($bindings as $key => $value) {
            $pdoStatement->bindValue(
                is_int($key) ? $key + 1 : $key,
                $value,
                is_int($value) || is_bool($value) ? PDO::PARAM_INT : PDO::PARAM_STR
            );
        }
        $pdoStatement->execute();
        return array($pdoStatement, microtime(true) - $start);
    }
691560
function Execute($sql)
	{
		$result = null;
		
		if ($this->ConnectionSetting->IsReadOnlySlave) {
			
			// this is a read-only slave connection attempting a write operation.  we
			// will only proceed if the connection specifies a "master" delegate connection
			if (!$this->_masterAdapter) {
				
				if ($this->ConnectionSetting->MasterConnectionDelegate) {
					
					$this->Observe("DataAdapter ($this->_label) (DataAdapter.Execute) Delegating write operation from Slave to Master Connection", OBSERVE_INFO);
				
					$this->_masterAdapter = new DataAdapter($this->ConnectionSetting->MasterConnectionDelegate);
					
					foreach ($this->_observers as $observer) {
						$this->_masterAdapter->AttachObserver($observer);
					}
				}
				else {
					throw new Exception('DB Write operation was attempted on a read-only slave connection');
				}
			}
			
			// we have a master connection initialized and ready to use
			$result = $this->_masterAdapter->Execute($sql);

		}
		else {
			$this->RequireConnection(true);
			$this->Observe("DataAdapter ($this->_label) (DataAdapter.Execute) " . $sql, OBSERVE_QUERY);
			$result = -1;
			
			try
			{
				$result = $this->_driver->Execute($this->_dbconn, $sql);
				$this->_num_retries = 0;
			}
			catch (Exception $ex)
			{
				// retry one time a communication error occurs
				if ($this->_num_retries == 0 && DataAdapter::$RETRY_ON_COMMUNICATION_ERROR && $this->IsCommunicationError($ex))
				{
					$this->_num_retries++;
					$this->Observe("DataAdapter ($this->_label) Communication error.  Retry attempt " . $this->_num_retries, OBSERVE_WARN);
					sleep(2); // slight delay to prevent throttling
					return $this->Execute($sql);
				}
				
				$msg = "DataAdapter ($this->_label)" . ' Error Executing SQL: ' . $ex->getMessage() . ' (retry attempts: '.$this->_num_retries.')';
				
				$this->Observe($msg,OBSERVE_FATAL);
				throw new Exception($msg,$ex->getCode());
			}
			}
		return $result;
	}
915575
public function exec($sql = "", $bindingValues = array(), $insert = true)
    {
        //Check if the query is a SELECT|INSERT|UPDATE and :variation is available
        if (preg_match("/.*(SELECT|INSERT|UPDATE|SHOW|DELETE).*/", $sql)) {
            
            $this->sql = $sql;

            //Always prepare the SQL statement first
            $query = $this->connection->prepare($sql);

            if (preg_match('/\s*:(.+?)\s/', $sql)) {
                if (is_array($bindingValues) && !empty($bindingValues)) {
                    foreach ($bindingValues as $key => $val) {
                        //Clean the bindingValues. Check if they start with :
                        if (!preg_match('/:.*/', $key)) {
                            $bindingValues[":" . $key] = $val;
                            unset($bindingValues[$key]);
                        }
                    }
                }


                //Add the binding variables to the query
                if ($query->execute($bindingValues)) {
                    return $this->getLastInsertID();
                } else {
                    //@ToDo:When the save or update fails make sure we handle the error gracefully!
                    throw new \Exception(implode("\n", $query->errorInfo()));
                }

            } else {
                $result = $query->execute();
            }

            if (preg_match('/.*(SELECT|SHOW).*/', $sql)) {
                $query->setFetchMode(\PDO::FETCH_ASSOC);
                return $query->fetchAll();
            }

            return $result;
        }


        return false;
    }
26682
public function values($sql, $bind, $cache = false) {
        $values = null;
        $dbCache = null;
        if ($cache) {
            /* @var $dbCache DBCache */
            $dbCache = Ioc::get(DBCache::class);
            $values = $dbCache->queryCache($sql, $bind);
        }
        if ($values == null) {
            $items = $this->query($sql, $bind);
            if ($items && count($items) > 0) {
                $item = $items[ 0 ];
                $key = array_keys($item)[ 0 ];
                $values = [];
                foreach ($items as $item) {
                    $values[] = $item[ $key ];
                }
                if ($cache) {
                    $dbCache->saveCache($sql, $bind, $values);
                }
            }
        }
        if (!$values) {
            $values = [];
        }
        return $values;
    }
935188
public function batchQuery($sqlArray = [], $bind = [])
    {
        if (!is_array($sqlArray)) {
            return false;
        }

        // 自动启动事务支持
        $this->startTrans();

        try {
            foreach ($sqlArray as $sql) {
                $this->execute($sql, $bind);
            }
            // 提交事务
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }

        return true;
    }
189939
public function execute(string $sql, $bind = []): Statement
    {
        $this->operation = 'execute';
        $this->sql = $sql;
        $this->params = $bind;
        return $this;
    }
347974
protected function _execute($sql, $bind)
    {
        if (!isset($this->_prepared[$sql])) {
            if (count($this->_prepared) > 8) {
                array_shift($this->_prepared);
            }
            $this->_prepared[$sql] = @$this->_getPdo()->prepare($sql);
        }
        $statement = $this->_prepared[$sql];

        foreach ($bind as $parameter => $value) {
            if (is_string($value)) {
                $type = \PDO::PARAM_STR;
            } elseif (is_int($value)) {
                $type = \PDO::PARAM_INT;
            } elseif (is_bool($value)) {
                $type = \PDO::PARAM_BOOL;
            } elseif ($value === null) {
                $type = \PDO::PARAM_NULL;
            } elseif (is_float($value)) {
                $type = \PDO::PARAM_STR;
            } elseif (is_array($value) || $value instanceof \JsonSerializable) {
                $type = \PDO::PARAM_STR;
                $value = json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            } else {
                throw new NotSupportedException(['The `:1` type of `:2` parameter is not support', $parameter, gettype($value)]);
            }

            if (is_int($parameter)) {
                $statement->bindValue($parameter + 1, $value, $type);
            } else {
                if ($parameter[0] === ':') {
                    throw new InvalidValueException(['Bind does not require started with `:` for `:parameter` parameter', 'parameter' => $parameter]);
                }

                $statement->bindValue(':' . $parameter, $value, $type);
            }
        }

        @$statement->execute();

        return $statement;
    }
670205
private function _queryPDO($sql, array $params = array())
    {
        try {
            $this->_queryId = self::$_linkId->prepare($sql);
            $i = 1;
            foreach ($params as $key => $val) {
                $type = $this->getPDOConstantType($val);
                $this->_queryId->bindValue($i, $val, $type);
                ++$i;
            }
            return $this->_queryId->execute();
        } catch (PDOException $e) {
            $this->_error = $e->getMessage();
            return false;
        }
    }
829545
public function go($bindId = null, $sql = null)
    {
        if ($sql == null) {
            $sql = $this->getStatement(false);
        }
        if (getInstance()->processType == \PG\MSF\Macro::PROCESS_TASKER) { // 如果是task进程自动转换为同步模式
            $profileName = $this->mysqlPool->getAsynName() . '(' . str_replace("\n", " ", $sql) . ')';
            $this->getContext()
                ->getLog()
                ->profileStart($profileName);
            
            $this->mergeInto($this->mysqlPool->getSync($this->getContext()));
            $this->clear();
            $data = array();
            switch ($sql) {
                case 'commit':
                    $this->mysqlPool->getSync($this->getContext())
                        ->pdoCommitTrans();
                    break;
                case 'begin':
                    $this->mysqlPool->getSync($this->getContext())
                        ->pdoBeginTrans();
                    break;
                case 'rollback':
                    $this->mysqlPool->getSync($this->getContext())
                        ->pdoRollBackTrans();
                    break;
                default:
                    $data = $this->mysqlPool->getSync($this->getContext())
                        ->pdoQuery($sql);
            }
            $this->getContext()
                ->getLog()
                ->profileEnd($profileName);
            return $data;
        } else {
            $this->clear();
            return $this->getObject(MySql::class, [
                $this->mysqlPool,
                $bindId,
                $sql
            ]);
        }
    }
1054226
public static function query($sql,$bind=[])
    {
        try{
            $bind=is_array($bind) ? $bind : [$bind];
            self::$db=Connect::boot();
            Connect::comSql($sql);
            $sth = self::$db->prepare($sql);
            $sth->execute($bind);
            $sth->setFetchMode(\PDO::FETCH_ASSOC);

            return $sth;
        } catch (\PDOException $e) {
            throw new Exception($e->getMessage());
            //View::throwError($error);
        }
    }
140101
public function exec(string $sql, array $bind = []): FetchAbstract
    {
        if ($bind) {
            $stmt = $this->handle->prepare($sql);
            foreach ($bind as $name => $val) {
                $type = $this->getArgType($val);
                $stmt->bindValue(':' . $name, $val, $type);
            }

            $result = $stmt->execute();
        } else {
            $result = $this->handle->query($sql);
        }

        return new SqliteFetch($sql, $result);
    }
1080740
public function bind($sql, array $params=array())
    {
        return $this->_bindInto('\?', $sql, $params, function($binder, $param) use ($sql) {
            return $binder->sqlValue($param);
        });
    }
582271
public function whereRaw($sql, $bindings = [], $boolean = 'and')
    {
        $this->wheres[] = ['type' => 'raw', 'sql' => $sql, 'boolean' => $boolean];

        $this->addBinding((array) $bindings, 'where');

        return $this;
    }
330064
public function query($callback, $bindId = null, $sql = null, Context $context = null)
    {
        if ($sql == null) {
            $sql = $this->dbQueryBuilder->getStatement(false);
            $this->dbQueryBuilder->clear();
        }
        if (empty($sql)) {
            throw new Exception('sql empty');
        }
        $data = [
            'sql' => $sql
        ];
        $data['token'] = $this->addTokenCallback($callback);
        if (! empty($bindId)) {
            $data['bind_id'] = $bindId;
        }
        // 写入管道
        $this->asynManager->writePipe($this, $data, $this->workerId);
    }
541202
public function execute($sql, $bind = [], $clear_cache = true) {
        $pdo = $this->connect();
        // 根据参数绑定组装最终的SQL语句
        $this->logSql($sql, $bind);
        //释放前次的查询结果
        $this->PDOStatement = null;
        if ($clear_cache) {
            /* @var $dbCache DBCache */
            $dbCache = Ioc::get(DBCache::class);
            $dbCache->deleteCache($sql);
        }
        try {
            // 调试开始
            // 预处理
            $this->PDOStatement = $pdo->prepare($sql);
            // 参数绑定
            $this->bindValue($bind);
            // 执行查询

            $this->PDOStatement->execute();
        } catch (\PDOException $e) {
            $error = $e->errorInfo;
            //2006和2013表示表示连接失败,需要重连接
            if ($error[ 1 ] == 2006 || $error[ 1 ] == 2013) {
                $this->pdo = null;
                $this->connect();
                $this->execute($sql, $bind);
            } else {
                throw $e;
            }
        }
    }
606673
public function bindClass($class, $alias = false) {

        $self  = $this;
        $clean = $alias ? $alias : \trim(\strtolower(\str_replace("\\", "/", $class)), "\\");

        $this->bind('/'.$clean.'/*', function() use($self, $class, $clean) {

            $parts      = \explode('/', \trim(\preg_replace("#$clean#","",$self["route"],1),'/'));
            $action     = isset($parts[0]) ? $parts[0]:"index";
            $params     = \count($parts)>1 ? \array_slice($parts, 1):[];

            return $self->invoke($class,$action, $params);
        });

        $this->bind('/'.$clean, function() use($self, $class) {
            return $self->invoke($class, 'index', []);
        });
    }