执行一个sql语句

@param Context $context
请求上下文对象
@param callable $callback
执行完成后的回调函数
@param int|null $bindId
绑定ID
@param string|null $sql
SQL语句
@throws Exception
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);
    }
495804
public function query($sqlStatement, $bindParams=null, $bindTypes=null) {
		try {
			$results = $this->callParentQuery($sqlStatement, $bindParams, $bindTypes);
            $results->setFetchMode(Db::FETCH_ASSOC);
            return $results;
		} catch(\PDOException $e) {
			if($e->getCode() === self::MYSQL_WENT_AWAY_CODE || $e->getMessage() === 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away') {
				$this->connect($this->_descriptor);
				return $this->callParentQuery($sqlStatement, $bindParams, $bindTypes);
			} else {
				throw $e;
			}
		}
	}
1359238
public function prepareAndExecuteSql($sql, $binds = [])
    {
        $prepare = $this->prepareSQL($sql, $binds);

        return $this->executePrepared($prepare);
    }
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
            ]);
        }
    }
331917
public function execute($sql = null, $parameters = array()) {
		if (empty($sql)) {
			return null;
		}
		try {
			if (!empty($sql)) {
				$this->prepare($sql);
				$this->bind($parameters);
			}
			$this->result->execute();
		} catch (\PDOException  $ex) {
            if (Config::isDebug()) {
                Factory::log()->info(sprintf('PDO: %s => %s', $sql, $this->error), $parameters);
                throw $ex;
            }
			$this->error = $ex->getMessage();
		}
        return $this->result;
	}
1038114
public Map<String, Object> executeForMap(int sqlId, Map<String, ? extends Object> bindParams) {
      String sql = context.getResources().getString(sqlId);
      return executeForMap(sql, bindParams);
   }
273812
public function _bindInto($pattern, $sql, $params, $func)
    {
        $result = NULL;

        // http://stackoverflow.com/questions/5695240/php-regex-to-ignore-escaped-quotes-within-quotes
        // this could be done with back refs, but this is much faster
        $regex = "/('[^'\\\\]*(?:\\\\.[^'\\\\]*)*'|\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"|$pattern)/";

        foreach (preg_split($regex, $sql, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY) as $token) {
            if ($token == '?' || ($token[0] != '"' && $token[0] != "'" && preg_match("/$pattern/", $token))) {
                if(!count($params))
                    throw new \InvalidArgumentException("Not enough parameters to bind($sql)");

                $result .= $func($this, array_shift($params), $token);
            } else {
                $result .= $token;
            }
        }

        if (count($params)) {
            $exception = new \InvalidArgumentException("Parameters left over in bind($sql)");
            $exception->leftOverParams = $params;
            throw $exception;
        }

        return $result;
    }
1197018
function query($query,$bind_arr = null){
    $stmt = $this->mysqli->prepare($query);
    if(!$stmt){
     throw new Exception("can't prepare query:[$query] because [".$this->mysqli->error."]");
    }
    if(isset($bind_arr) && $bind_arr != null){
      call_user_func_array(array($stmt,'bind_param'),$this->makeValuesReferenced($bind_arr));
    }
    /* execute prepared statement */
    if(!$stmt->execute()){
       throw new Exception( $this->mysqli->error );
    }
    $answer = $this->fetch($stmt);
    $stmt->close();
    return $answer;
  }
840171
protected function runQueryCallback($query, $bindings, Closure $callback)
    {
        // To execute the statement, we'll simply call the callback, which will actually
        // run the SQL against the PDO connection. Then we can calculate the time it
        // took to execute and log the query SQL, bindings and time in our memory.
        try {
            $result = $callback($query, $bindings);
        }

            // If an exception occurs when attempting to run a query, we'll format the error
            // message to include the bindings with SQL, which will make this exception a
            // lot more helpful to the developer instead of just the database's errors.
        catch (Exception $e) {
            throw new QueryException(
                $query, $bindings, $e
            );
        }

        return $result;
    }
988733
function bind (callback, context) {
  var args = arraySlice(arguments, 2)
  context = context || this
  return function () {
    return callback.apply(context, arraySlice(arguments).concat(args))
  }
}
586252
public function query($sql, $data = [])
     {
         $this->_init();

         try {
             $q = $this->db->prepare($sql);
         } catch (PDOException $e) {
             throw new Exception($e->getMessage());
         }

         foreach ($data as $k => $v) {
             $$k = $v;
             $q->bindParam(':' . $k, $$k); # bindParam( ... , PDO::PARAM_INT ...);
         }

         $result = $q->execute();

         if (strpos(trim(strtoupper($sql)), 'SELECT') === 0) {
             $rows = [];
             while($row = $q->fetch()) {
                 $rows[] = $row;
             }
             return $rows;
         }

         return $result;
     }
262260
public function query($sql, $bind = [], $master = false, $pdo = false)
    {
        $this->initConnect($master);

        if (!$this->linkID) {
            return false;
        }

        // 记录SQL语句
        $this->queryStr = $sql;

        $this->bind = $bind;

        Db::$queryTimes++;

        try {
            // 调试开始
            $this->debug(true);

            // 预处理
            $this->PDOStatement = $this->linkID->prepare($sql);

            // 是否为存储过程调用
            $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);

            // 参数绑定
            if ($procedure) {
                $this->bindParam($bind);
            } else {
                $this->bindValue($bind);
            }

            // 执行查询
            $this->PDOStatement->execute();

            // 调试结束
            $this->debug(false, '', $master);

            // 返回结果集
            return $this->getResult($pdo, $procedure);
        } catch (\PDOException $e) {
            if ($this->isBreak($e)) {
                return $this->close()->query($sql, $bind, $master, $pdo);
            }

            throw new PDOException($e, $this->config, $this->getLastsql());
        } catch (\Throwable $e) {
            if ($this->isBreak($e)) {
                return $this->close()->query($sql, $bind, $master, $pdo);
            }

            throw $e;
        } catch (\Exception $e) {
            if ($this->isBreak($e)) {
                return $this->close()->query($sql, $bind, $master, $pdo);
            }

            throw $e;
        }
    }
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;
	}
798490
protected function _afterSelect(DatabaseContext $context)
    {
        if(!$context->query->isCountQuery())
        {
            $rowset = ObjectConfig::unbox($context->data);

            if ($rowset instanceof DatabaseRowsetInterface)
            {
                //Store the nodes
                $this->__nodes    = $rowset;
                $this->__iterator = null;
                $this->__children = array();

                foreach ($this->__nodes as $key => $row)
                {
                    //Force mixin the behavior into each row
                    $row->mixin($this);

                    if($row->isRecursable()) {
                        $parent = (int) $row->getProperty($this->_parent_column);
                    } else {
                        $parent = 0;
                    }

                    //Store the nodes by parent
                    $this->__children[$parent][$key] = $row;
                }

                //Sort the children
                ksort($this->__children);
            }
        }
    }
631714
public function execute($sql, $bind = [], $has_insert_id = false)
    {
        $sql = $this->_replaceQuoteCharacters($sql);

        try {
            $r = $bind ? $this->_execute($sql, $bind)->rowCount() : @$this->_getPdo()->exec($sql);
            if ($has_insert_id) {
                return $this->_getPdo()->lastInsertId();
            } else {
                return $r;
            }
        } catch (\PDOException $e) {
            throw new DbException([
                ':message => ' . PHP_EOL . 'SQL: ":sql"' . PHP_EOL . ' BIND: :bind',
                'message' => $e->getMessage(),
                'sql' => $sql,
                'bind' => json_encode($bind, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
            ]);
        }
    }
551129
public boolean execute() throws SQLException {
        boolean isExceptionThrown = ExecutorExceptionHandler.isExceptionThrown();
        SQLExecuteCallback<Boolean> executeCallback = SQLExecuteCallbackFactory.getPreparedSQLExecuteCallback(getDatabaseType(), isExceptionThrown);
        List<Boolean> result = executeCallback(executeCallback);
        if (null == result || result.isEmpty() || null == result.get(0)) {
            return false;
        }
        return result.get(0);
    }
1256290
public function visit($query, $node, string $context)
    {
        if ($node instanceof $this->node) {
            $bindings = [];
            $sql = [];

            $child0 = $node->getChildByIndex(0);
            $child1 = $node->getChildByIndex(1);

            if ($child0 instanceof Nodes\KeyNode) {
                $context === Nodes\OrNode::class && $query->orWhereNotNull($this->parseKey($child0->getValue()));
                $context === Nodes\AndNode::class && $query->whereNotNull($this->parseKey($child0->getValue()));
            }
        }
    }