执行数据库query

如果是SELECT\show查询可以后续操作，如findAll

@param string $sql 要查询的SQL或执行commit的SQL等
@param array $replacement 按照位置替换问号“？”
@return mixed
195070
public function query($sql, $replacement = array())
    {
        if (!empty($replacement)) {
            // 支持model->query("cid=? and name=?", [12, "name"])
            $i   = 0;
            $sql = preg_replace_callback(["/(\?)/"], function () use (&$i, &$replacement) {
                $v = $replacement[$i++];
                return !is_string($v) ? $v : "'" . $this->escape_string($v) . "'";
            }, $sql);
        }

        // 鉴定是执行查询还是commit提交操作。如果是select、show，可以有后续操作。
        $_key = strtolower(substr($sql, 0, 4));
        if ($_key == 'sele' || $_key == 'show') {
            $this->query_sql = $sql;
            return $this;
        } else {
            $this->sql = $sql;
            return $this->conn()->query($sql);
        }
    }
608150
public function _replaceUrlInDump($sql)
    {
        if ($this->config['urlReplacement'] === false) {
            return $sql;
        }

        $this->dbDump->setTablePrefix($this->config['tablePrefix']);
        $this->dbDump->setUrl($this->config['url']);

        if (\is_array($sql)) {
            $sql = $this->dbDump->replaceSiteDomainInSqlArray($sql);
            $sql = $this->dbDump->replaceSiteDomainInMultisiteSqlArray($sql);
        } else {
            $sql = $this->dbDump->replaceSiteDomainInSqlString($sql, true);
            $sql = $this->dbDump->replaceSiteDomainInMultisiteSqlString($sql, true);
        }

        return $sql;
    }
1166855
public static function splitSql($sql)
  {
    $start = 0;
    $open = false;
    $char = '';
    $end = strlen($sql);
    $queries = [];

    for($i=0; $i<$end; $i++){
      $current = substr($sql, $i, 1);
      if ( $current == '"' || $current == '\'' ){
        $n = 2;

        while(substr($sql, $i - $n + 1, 1) == '\\' && $n < $i){
          $n++;
        }

        if ( $n % 2 == 0 ){
          if ( $open ){
            if ( $current == $char ){
              $open = false;
              $char = '';
            }
          }
          else {
            $open = true;
            $char = $current;
          }
        }
      }

      if ( ($current == ';' && !$open) || $i == $end - 1 ){
        $queries[] = substr($sql, $start, ($i - $start + 1));
        $start = $i + 1;
      }
    }

    return $queries;
  }
1215317
public function query($sql)
    {
        // get start time of sql execution
        $start = $this->_firebug->timer();
        // execute sql
        $records = $this->_pdo->query($sql);
        // record sql statement
        if ($this->_firebug->isEnabled()) {
            $trace = debug_backtrace();
            $this->_recordSqlStatement($start, $sql, $trace);
        }

        return $records;
    }
654307
public function query($sql)
    {
        if (true == Config::get('sql_log')) {
            wlog('SQL-Log', $sql);
        }

        // Prepare one MySQL client connect
        $isFromPool = $this->prepareDB();

        try {
            $rs = $this->db->query($sql);
        } catch (\Exception $e) {
            // echo 'error:'. $e->getCode() . $e->getMessage();
            // 如果发生了mysqli::query(): MySQL server has gone away，直接抛出异常，
            // 需要捕获后，重新reconnect
        }

        if ( !empty($rs) ) {
            $GLOBALS['__$DB_QUERY_COUNT']++;
        } else if($this->db->errno == 2006 || $this->db->errno == 2013) {
            // Catch database pool long running
            // 2013 Lost connection to MySQL server during query
            // 2006 MySQL server has gone away
            try {
                $this->reconnect();
            } catch (\Exception $e) {
                DBPool::init($this->db_config)->cap--;
                DBPool::init($this->db_config)->activeCount--;
                \throw_error('DB_ERROR: ' . $this->db->error . "\nRAW_SQL: " . $sql, $this->db->errno);
            }

            $GLOBALS['__$DB_QUERY_COUNT']++;
            $rs = $this->db->query($sql);
        } else {
            DBPool::init($this->db_config)->cap--;
            DBPool::init($this->db_config)->activeCount--;
            \throw_error('DB_ERROR: ' . $this->db->error . "\nRAW_SQL: " . $sql, $this->db->errno);
        }

        // Put db connction to pool
        // If it is new client, queue in, else put pool client back
        if ($isFromPool) {
            DBPool::init($this->db_config)->back($this->db);
        } else {
            DBPool::init($this->db_config)->in($this->db);
        }

        // echo 'db_config='. $this->db_config;
        // echo 'activeCount='. (DBPool::init($this->db_config)->activeCount);
        // echo ',cap='. (DBPool::init($this->db_config)->cap);
        // var_dump(DBPool::init($this->db_config)->queue);

        return $rs;
    }
884659
protected function execute($sql)
    {
        $this->lastQuery = $sql;

        $this->debugLog(sprintf('Executing SQL: %s', $sql));

        $this->sqlStatement = $this->getConnection()->prepare($sql, []);
        $this->sqlStatement->execute();
        $this->lastId = $this->connection->lastInsertId(sprintf('%s_id_seq', $this->getEntity()));

        // If their is an id, save it!
        if ($this->lastId) {
            $this->handleLastId($this->getEntity(), $this->lastId);
        }

        return $this->sqlStatement;
    }
1197634
protected function _execute($sql)
	{
		return $this->is_write_type($sql)
			? $this->conn_id->exec($sql)
			: $this->conn_id->query($sql);
	}
1219284
protected function sql($sql = null, $replace = false)
    {
        if (null !== $sql) {
            if (!isset($this->oosql_sql[$this->oosql_table]) || $replace) {
                $this->oosql_sql[$this->oosql_table] = $sql;
            } else {

                $this->oosql_sql[$this->oosql_table] .= $sql;
            }
            return;
        }
        return $this->oosql_sql[$this->oosql_table];
    }
603799
public function exec($sql) {
        $dialect = $this->dialect;
        if (is_null($dialect)) {
            return false;
        }
        try {
            // 表前缀处理
            $sql = preg_replace_callback('#\{[a-z][a-z0-9_].*\}#i', function ($r) use ($dialect) {
                return $dialect->getTableName($r[0]);
            }, $sql);

            return false !== $dialect->exec($sql);
        } catch (\Exception $e) {
            $this->error = $e->getMessage();

            return false;
        }
    }
737181
protected function _execute($sql)
	{
		return ibase_query(isset($this->_ibase_trans) ? $this->_ibase_trans : $this->conn_id, $sql);
	}
85104
public function replace_all_text($table, database_column_info $column, $search, $replace) {
        if (!$this->replace_all_text_supported()) {
            return;
        }

        // NOTE: override this methods if following standard compliant SQL
        //       does not work for your driver.

        // Enclose the column name by the proper quotes if it's a reserved word.
        $columnname = $this->get_manager()->generator->getEncQuoted($column->name);

        $searchsql = $this->sql_like($columnname, '?');
        $searchparam = '%'.$this->sql_like_escape($search).'%';

        $sql = "UPDATE {".$table."}
                       SET $columnname = REPLACE($columnname, ?, ?)
                     WHERE $searchsql";

        if ($column->meta_type === 'X') {
            $this->execute($sql, array($search, $replace, $searchparam));

        } else if ($column->meta_type === 'C') {
            if (core_text::strlen($search) < core_text::strlen($replace)) {
                $colsize = $column->max_length;
                $sql = "UPDATE {".$table."}
                       SET $columnname = " . $this->sql_substr("REPLACE(" . $columnname . ", ?, ?)", 1, $colsize) . "
                     WHERE $searchsql";
            }
            $this->execute($sql, array($search, $replace, $searchparam));
        }
    }
1307572
protected function query($sql) {
        $vars = func_get_args();
		$cleaner = "/[\s,].+|[^a-zA-Z]/";
		$illegal = "/[\\\\'\"\%]/";
        try {
            $pdo = $this->dbConnect();
            $stmt = $pdo->prepare($sql);
            $binds = explode(':', $sql);
            foreach($binds as $n => $b) {
				if($n != 0 && substr($b,1)!=false) {
					$b = ':' . preg_replace($cleaner,'',$b);
					$vars[$n] = preg_replace($illegal,'',$vars[$n]);
					$stmt->bindParam($b,$vars[$n]);
				}
            }
            $stmt->execute();
            return (strpos($sql,'SELECT') !== FALSE) ? $stmt->fetchAll() : true;
        } catch(PDOException $e) {
            return array('query_error' => $e);
        }
    }
531111
public function replace($column, $target, $replacement)
    {
        $this->queryBuilder->replace($column, $target, $replacement);
        return $this;
    }
266547
public function selectValues($sql)
    {
        $result = $this->execute($sql);
        if ($result->count()) {
            $values = [];
            foreach ($result as $row) {
                $values[] = reset($row);
            }
            return $values;
        }
    }
383003
public static function fetchAll($sql) {
		$return = array();
		$results = \Database::getInstance()->query($sql);
		while ($result = $results->fetchAssoc()) {
			$return[$result['id']] = $result;
		}
		return $return;
	}
502572
final public function execute($sql)
    {
        if (!$this->DB) {
            throw  new Exception('您还没有连接数据库', Exception::CODE_DATABASE_ERROR);
        }
        $this->lastQueryAt = time();
        return $this->DB->execute($sql);
    }
1321718
public function getAll($sql, $params = array())
    {
        $stmt = $this->execute($sql, $params);
        return $stmt->fetchAll($this->fetchMode);
    }