执行MySQL SQL

@param array $data
执行的SQL信息
@throws Exception
181171
public function execute($data)
    {
        $client = null;
        $bindId = $data['bind_id'] ?? null;
        if ($bindId != null) { // 绑定
            $client = $this->bindPool[$bindId]['client'] ?? null;
            $sql = strtolower($data['sql']);
            if ($sql != 'begin' && $client == null) {
                throw new Exception('error mysql affairs not begin.');
            }
        }
        if ($client == null) {
            if (count($this->pool) == 0) { // 代表目前没有可用的连接
                $this->prepareOne();
                $this->commands->push($data);
                return;
            } else {
                $client = $this->pool->shift();
                if ($client->isClose ?? false) {
                    $this->reconnect($client);
                    $this->commands->push($data);
                    return;
                }
                
                if ($bindId != null) { // 添加绑定
                    $this->bindPool[$bindId]['client'] = $client;
                }
            }
        }
        
        $sql = $data['sql'];
        $client->query($sql, function ($client, $result) use ($data) {
            if ($result === false) {
                if ($client->errno == 2006 || $client->errno == 2013) { // 断线重连
                    $this->reconnect($client);
                    if (! isset($data['bind_id'])) { // 非事务可以重新执行
                        $this->commands->unshift($data);
                    }
                    return;
                    // 发生错误
                } else {
                    // 事务出错不需要自动回滚，否则会带来新问题，调整为手工回滚（modified by xudianyang）
                    // if (isset($data['bind_id'])) {
                    // $data['sql'] = 'rollback';
                    // $this->commands->push($data);
                    // }
                    // 设置错误信息
                    $data['result']['error'] = "[mysql]:" . $client->error . "[sql]:" . $data['sql'];
                }
            }
            $sql = strtolower($data['sql']);
            if ($sql == 'begin') {
                $data['result'] = $data['bind_id'];
            } else {
                $data['result']['client_id'] = $client->client_id;
                $data['result']['result'] = $result;
                $data['result']['affected_rows'] = $client->affected_rows;
                $data['result']['insert_id'] = $client->insert_id;
            }
            // 给worker发消息
            $this->asynManager->sendMessageToWorker($this, $data);
            
            // 不是绑定的连接就回归连接
            if (! isset($data['bind_id'])) {
                $this->pushToPool($client);
            } else { // 事务
                $bindId = $data['bind_id'];
                if ($sql == 'commit' || $sql == 'rollback') { // 结束事务
                    $this->freeBind($bindId);
                }
            }
        });
    }
134857
public function delete($data = null)
    {
        // 分析查询表达式
        $options = $this->parseExpress();
        $pk      = $this->getPk($options);
        if (isset($options['cache']) && is_string($options['cache']['key'])) {
            $key = $options['cache']['key'];
        }

        if (!is_null($data) && true !== $data) {
            if (!isset($key) && !is_array($data)) {
                // 缓存标识
                $key = 'think:' . $options['table'] . '|' . $data;
            }
            // AR模式分析主键条件
            $this->parsePkWhere($data, $options);
        } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'][$pk])) {
            $key = $this->getCacheKey($options['where']['AND'][$pk], $options, $this->bind);
        }

        if (true !== $data && empty($options['where'])) {
            // 如果条件为空 不进行删除操作 除非设置 1=1
            throw new Exception('delete without condition');
        }
        // 生成删除SQL语句
        $sql = $this->builder->delete($options);
        // 获取参数绑定
        $bind = $this->getBind();
        if ($options['fetch_sql']) {
            // 获取实际执行的SQL语句
            return $this->connection->getRealSql($sql, $bind);
        }

        // 执行操作
        $result = $this->execute($sql, $bind);
        if ($result) {
            if (!is_array($data) && is_string($pk) && isset($key) && strpos($key, '|')) {
                list($a, $val) = explode('|', $key);
                unset($a);
                $item[$pk]     = $val;
                $data          = $item;
            }
            $options['data'] = $data;
            $this->trigger('after_delete', $options);
        }
        return $result;
    }
1237529
public function insert(array $data)
    {
        $person_id = empty($data['person_id']) ? 0 : (int) $data['person_id'];
        if ($person_id <= 0) {
            throw new Exception('Required field person_id');
        }
        unset($data['person_id']);

        return $this->rest->post("people/$person_id/$this->action", $data);
    }
95187
public function update(array $statements, array $data): array
    {
        if (\count($data) === 0) {
            throw new Exception('No data given.', 4);
        }

        $table = end($statements['tables']);

        // UPDATE
        [$updateStatement, $bindings] = $this->getUpdateStatement($data);

        // WHERE
        [$whereCriteria, $whereBindings] = $this->buildCriteriaWithType($statements, 'wheres', 'WHERE');

        $sqlArray = [
            'UPDATE',
            $this->wrapSanitizer($table),
            $this->buildQueryPart(static::QUERY_PART_JOIN, $statements),
            'SET ' . $updateStatement,
            $whereCriteria,
            $this->buildQueryPart(static::QUERY_PART_GROUPBY, $statements),
            $this->buildQueryPart(static::QUERY_PART_ORDERBY, $statements),
            $this->buildQueryPart(static::QUERY_PART_LIMIT, $statements),
            $this->buildQueryPart(static::QUERY_PART_OFFSET, $statements),
        ];

        $sql = $this->concatenateQuery($sqlArray);

        $bindings = array_merge($bindings, $whereBindings);

        return compact('sql', 'bindings');
    }
272138
public void runSql( String sql ) throws Exception {
        String[] sqlSplit = sql.split("\n");
        StringBuilder sb = new StringBuilder();
        for( String string : sqlSplit ) {
            String trim = string.trim();
            if (trim.length() == 0) {
                continue;
            }
            if (trim.startsWith("--")) {
                continue;
            }
            sb.append(trim + " ");
        }

        String[] sqls = sb.toString().split(";");
        for( String single : sqls ) {
            executeInsertUpdateDeleteSql(single);
        }
    }
381347
public function executeSql()
    {
        $params = func_get_args();
        $sql = array_shift($params);

        if (!$sql)
            throw new Exception\LogicException("Can't execute SQL without SQL");
        elseif (is_array($sql)) {
            $params = $sql;
            $sql = array_shift($params);
        }
        $this->_parse_query_multimark($sql, $params);

        if (!$stmt = $this->pdo->prepare($sql)) {
            list($code, $drvrcode, $msg) = $this->pdo->errorInfo();
            $e = new Exception\QueryException(
                sprintf("[PDOStatement error] [SQLSTATE %s] (%s) %s", $code, $drvrcode, $msg)
            );
            throw $e;
        } elseif (!$stmt->execute($params) && Rails::env() == 'development') {
            list($code, $drvrcode, $msg) = $stmt->errorInfo();
            $e = new Exception\QueryException(
                sprintf("[PDOStatement error] [SQLSTATE %s] (%s) %s", $code, $drvrcode, $msg)
            );
            $e->setStatement($stmt, $params);
            throw $e;
        }

        $err = $stmt->errorInfo();

        if ($err[2]) {
            ActiveRecord::setLastError($err, $this->name);
            $e = new Exception\QueryException(
                sprintf("[SQLSTATE %s] (%s) %s", $err[0], (string)$err[1], $err[2])
            );
            $e->setStatement($stmt, $params);

            $msg  = "Error on database query execution\n";
            $msg .= $e->getMessage();
            Rails::log()->warning($msg);
        }

        return $stmt;
    }
567356
public static function execute($conn, $sql) {
    $conn = is_array($conn) ? self::connect($conn) : $conn;
    $result = $conn->query($sql);
    if (!$result) {
      throw new SqlException("Cannot execute $sql: " . $conn->error);
    }

    if ($result && $result !== TRUE) {
      $result->free_result();
    }

  }
1211230
public function insert(array $data): int
    {
        $this->builder->setInsertData($data);
        $sql = $this->builder->buildSql();
        $this->builder = new QueryBuilder($this->pdo);
        return $this->execSql($sql);
    }
525076
public function copyFrom($data)
    {
        if (is_array($data) || $data instanceof \Traversable) {
            if ($this->getCount() > 0) {
                $this->clear();
            }
            if ($data instanceof CMap) {
                $data = $data->_data;
            }
            foreach ($data as $key => $value) {
                $this->add($key, $value);
            }
        } elseif ($data !== null) {
            throw new Exception('实例化列表参数必须是数组或可遍历的对象', 100100601);
        }
    }
875211
public function update($table = '', $data = array())
    {
        if (empty($data)) {
            die('数据不能为空！');
        }

        $sql = 'UPDATE '.$table.' SET ';
        //字段名处理
        foreach ($data as $k => $v) {
            $sql = $sql.$k.'=:'.$k.',';

            $this->bindParam($k, $v);
        }
        $sql = rtrim($sql, ',');
        $sql = $sql.' WHERE id='.$data['id'];

        return $this->execute($sql);
    }
848231
public function run_insert($sql, array $params=null, $seqName=null, array $driverOptions=array()) {
		
		#$this->sth = $this->dbh->prepare($sql, $driverOptions);
		#$this->sth->execute($params);
		$numRows = $this->run_query($sql, $params, $driverOptions);
		
		if($numRows > 0 && is_object($this->dbh)) {
			$retval = $this->dbh->lastInsertId($seqName);
		}
		else {
			throw new \Exception(__METHOD__ .": insert failed");
		}
		
		#$retval = $this->dbh->lastInsertId($seqName);
		return($retval);
	}
172417
public function write(string $data): void
	{
		if ($this->connected() === false)
		{
			throw new \Exception('Not connected');
		}

		fwrite($this->connection, $data);
	}
416429
public function rows(array $data): void
    {
        $this->rows = $data;
        $pdoStatement = $this->provideStatement();
        $this->execute($pdoStatement);
    }
1178314
public function query($sql, array $args = [])
    {
        if ($args) {
            $sql = \wf\db\QueryBuilder::format($sql, $args);
        }
        $sql = \wf\db\QueryBuilder::tablePrefix($sql, $this->cfg['tablePrefix']);
                            
        // 记录数据库查询次数
        $this->execTimes ++;
        $this->log[] = $sql;
        
        $query = $this->dbh->query($sql);        
        if(false === $query) {
            $this->log[] = $this->getLastErr();
            throw new \wf\db\Exception($this->getLastErr());
        }
        
        return $query;
    }
1217191
public function run_query($sql, array $params=null, array $driverOptions=array()) {
		try {
			$this->sth = null;
			$this->sth = $this->dbh->prepare($sql, $driverOptions);
			if($this->sth === false) {
				throw new \Exception(__METHOD__ .": STH is false... ". ToolBox::debug_print($this->dbh->errorInfo(),0));
			}
			// TODO: throw an exception on error (and possibly if there were no rows returned)
			$this->sth->execute($params); 
			$this->numRows = $this->sth->rowCount();
		}
		catch(PDOException $px) {
			throw new \Exception(__METHOD__ .": ". $px->getMessage());
		}
		return($this->numRows);
	}
58656
public function execute($sql) {

        //如果开启了调试模式，那么把所有对数据库写操作的语句记录下来
        if ( SQL_LOG &&
            (strpos($sql, 'INSERT') !== false
                || strpos($sql, 'DELETE') !== false
                || strpos($sql, 'REPLACE') !== false
                    || strpos($sql, 'UPDATE') !== false)) {
            Log::info($sql, 'sql');
        }
        if ( $this->link == null ) $this->connect();
        try {
            $result = $this->link->query($sql);
        } catch ( PDOException $e ) {
            $exception = new DBException("SQL错误:" . $e->getMessage());
            $exception->setCode($e->getCode());
            $exception->setQuery($sql);
            if ( APP_DEBUG ) {
                __print($sql);
            }
            throw $exception;
        }
        return $result;
    }
156077
public function exec($sql_string)
	{
		$this->sql_string = $sql_string;
		$query = sasql_query( $this->connection, $this->sql_string );
		if ( $query ) {
			return new SQLAnywhereQuery( $query, $this->connection );
		} else {
			throw new Exception("SQL String Problem :: " . sasql_error( $this->connection ), 110);		
		}
		return 0;
	}