没有命名空间的类 yii yii\base yii\behaviors yii\caching yii\captcha yii\console yii\console\controllers yii\console\widgets yii\data yii\db yii\db\conditions yii\db\cubrid yii\db\cubrid\conditions yii\db\mssql yii\db\mssql\conditions yii\db\mysql yii\db\oci yii\db\oci\conditions yii\db\pgsql yii\db\sqlite yii\db\sqlite\conditions yii\di yii\filters yii\filters\auth yii\grid yii\helpers yii\i18n yii\log yii\mail yii\mutex yii\rbac yii\rest yii\test yii\validators yii\web yii\widgets

Class yii\db\Connection

继承yii\db\Connection » yii\base\Component » yii\base\BaseObject
实现yii\base\Configurable
可用版本自2.0
源码 https://github.com/yiichina/yii2/blob/api/framework/db/Connection.php

Connection represents a connection to a database via PDO.

Connection works together with yii\db\Command, yii\db\DataReader and yii\db\Transaction to provide data access to various DBMS in a common set of APIs. They are a thin wrapper of the PDO PHP extension.

Connection supports database replication and read-write splitting. In particular, a Connection component can be configured with multiple $masters and $slaves. It will do load balancing and failover by choosing appropriate servers. It will also automatically direct read operations to the slaves and write operations to the masters.

To establish a DB connection, set $dsn, $username and $password, and then call open() to connect to the database server. The current state of the connection can be checked using $isActive.

The following example shows how to create a Connection instance and establish the DB connection:

$connection = new \yii\db\Connection([
    'dsn' => $dsn,
    'username' => $username,
    'password' => $password,
]);
$connection->open();

After the DB connection is established, one can execute SQL statements like the following:

$command = $connection->createCommand('SELECT * FROM post');
$posts = $command->queryAll();
$command = $connection->createCommand('UPDATE post SET status=1');
$command->execute();

One can also do prepared SQL execution and bind parameters to the prepared SQL. When the parameters are coming from user input, you should use this approach to prevent SQL injection attacks. The following is an example:

$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
$command->bindValue(':id', $_GET['id']);
$post = $command->query();

For more information about how to perform various DB queries, please refer to yii\db\Command.

If the underlying DBMS supports transactions, you can perform transactional SQL queries like the following:

$transaction = $connection->beginTransaction();
try {
    $connection->createCommand($sql1)->execute();
    $connection->createCommand($sql2)->execute();
    // ... executing other SQL statements ...
    $transaction->commit();
} catch (Exception $e) {
    $transaction->rollBack();
}

You also can use shortcut for the above like the following:

$connection->transaction(function () {
    $order = new Order($customer);
    $order->save();
    $order->addItems($items);
});

If needed you can pass transaction isolation level as a second parameter:

$connection->transaction(function (Connection $db) {
    //return $db->...
}, Transaction::READ_UNCOMMITTED);

Connection is often used as an application component and configured in the application configuration like the following:

'components' => [
    'db' => [
        'class' => '\yii\db\Connection',
        'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ],
],

公共属性

隐藏继承的属性

属性类型描述被定义在
$attributes array PDO attributes (name => value) that should be set when calling open() to establish a DB connection. yii\db\Connection
$behaviors yii\base\Behavior[] List of behaviors attached to this component yii\base\Component
$charset string The charset used for database connection. yii\db\Connection
$commandClass string The class used to create new database yii\db\Command objects. yii\db\Connection
$commandMap array Mapping between PDO driver names and yii\db\Command classes. yii\db\Connection
$driverName string Name of the DB driver yii\db\Connection
$dsn string The Data Source Name, or DSN, contains the information required to connect to the database. yii\db\Connection
$emulatePrepare boolean Whether to turn on prepare emulation. yii\db\Connection
$enableLogging boolean Whether to enable logging of database queries. yii\db\Connection
$enableProfiling boolean Whether to enable profiling of opening database connection and database queries. yii\db\Connection
$enableQueryCache boolean Whether to enable query caching. yii\db\Connection
$enableSavepoint boolean Whether to enable [savepoint](http://en. yii\db\Connection
$enableSchemaCache boolean Whether to enable schema caching. yii\db\Connection
$enableSlaves boolean Whether to enable read/write splitting by using $slaves to read data. yii\db\Connection
$isActive boolean Whether the DB connection is established yii\db\Connection
$lastInsertID string The row ID of the last row inserted, or the last value retrieved from the sequence object yii\db\Connection
$master yii\db\Connection The currently active master connection. yii\db\Connection
$masterConfig array The configuration that should be merged with every master configuration listed in $masters. yii\db\Connection
$masterPdo PDO The PDO instance for the currently active master connection. yii\db\Connection
$masters array List of master connection configurations. yii\db\Connection
$password string The password for establishing DB connection. yii\db\Connection
$pdo PDO The PHP PDO instance associated with this DB connection. yii\db\Connection
$pdoClass string Custom PDO wrapper class. yii\db\Connection
$queryBuilder yii\db\QueryBuilder The query builder for the current DB connection. yii\db\Connection
$queryCache yii\caching\CacheInterface|string The cache object or the ID of the cache application component that is used for query caching. yii\db\Connection
$queryCacheDuration integer The default number of seconds that query results can remain valid in cache. yii\db\Connection
$schema yii\db\Schema The schema information for the database opened by this connection. yii\db\Connection
$schemaCache yii\caching\CacheInterface|string The cache object or the ID of the cache application component that is used to cache the table metadata. yii\db\Connection
$schemaCacheDuration integer Number of seconds that table metadata can remain valid in cache. yii\db\Connection
$schemaCacheExclude array List of tables whose metadata should NOT be cached. yii\db\Connection
$schemaMap array Mapping between PDO driver names and yii\db\Schema classes. yii\db\Connection
$serverRetryInterval integer The retry interval in seconds for dead servers listed in $masters and $slaves. yii\db\Connection
$serverStatusCache yii\caching\CacheInterface|string|false The cache object or the ID of the cache application component that is used to store the health status of the DB servers specified in $masters and $slaves. yii\db\Connection
$serverVersion string Server version as a string. yii\db\Connection
$shuffleMasters boolean Whether to shuffle $masters before getting one. yii\db\Connection
$slave yii\db\Connection The currently active slave connection. yii\db\Connection
$slaveConfig array The configuration that should be merged with every slave configuration listed in $slaves. yii\db\Connection
$slavePdo PDO The PDO instance for the currently active slave connection. yii\db\Connection
$slaves array List of slave connection configurations. yii\db\Connection
$tablePrefix string The common prefix or suffix for table names. yii\db\Connection
$transaction yii\db\Transaction|null The currently active transaction. yii\db\Connection
$username string The username for establishing DB connection. yii\db\Connection

公共方法

隐藏继承的方法

方法描述被定义在
__call() Calls the named method which is not a class method. yii\base\Component
__clone() Reset the connection after cloning. yii\db\Connection
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__sleep() Close the connection before serializing. yii\db\Connection
__unset() Sets a component property to be null. yii\base\Component
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
beginTransaction() Starts a transaction. yii\db\Connection
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
cache() Uses query cache for the queries performed with the callable. yii\db\Connection
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
close() Closes the currently active DB connection. yii\db\Connection
createCommand() Creates a command for execution. yii\db\Connection
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getDriverName() Returns the name of the DB driver. Based on the the current $dsn, in case it was not set explicitly by an end user. yii\db\Connection
getIsActive() Returns a value indicating whether the DB connection is established. yii\db\Connection
getLastInsertID() Returns the ID of the last inserted row or sequence value. yii\db\Connection
getMaster() Returns the currently active master connection. yii\db\Connection
getMasterPdo() Returns the PDO instance for the currently active master connection. yii\db\Connection
getQueryBuilder() Returns the query builder for the current DB connection. yii\db\Connection
getQueryCacheInfo() Returns the current query cache information. yii\db\Connection
getSchema() Returns the schema information for the database opened by this connection. yii\db\Connection
getServerVersion() Returns a server version as a string comparable by \version_compare(). yii\db\Connection
getSlave() Returns the currently active slave connection. yii\db\Connection
getSlavePdo() Returns the PDO instance for the currently active slave connection. yii\db\Connection
getTableSchema() Obtains the schema information for the named table. yii\db\Connection
getTransaction() Returns the currently active transaction. yii\db\Connection
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the object. yii\base\BaseObject
noCache() Disables query cache temporarily. yii\db\Connection
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
open() Establishes a DB connection. yii\db\Connection
quoteColumnName() Quotes a column name for use in a query. yii\db\Connection
quoteSql() Processes a SQL statement by quoting table and column names that are enclosed within double brackets. yii\db\Connection
quoteTableName() Quotes a table name for use in a query. yii\db\Connection
quoteValue() Quotes a string value for use in a query. yii\db\Connection
setDriverName() Changes the current driver name. yii\db\Connection
setQueryBuilder() Can be used to set yii\db\QueryBuilder configuration via Connection configuration array. yii\db\Connection
transaction() Executes callback provided in a transaction. yii\db\Connection
trigger() Triggers an event. yii\base\Component
useMaster() Executes the provided callback by using the master connection. yii\db\Connection

受保护的方法

隐藏继承的方法

方法描述被定义在
createPdoInstance() Creates the PDO instance. yii\db\Connection
initConnection() Initializes the DB connection. yii\db\Connection
openFromPool() Opens the connection to a server in the pool. yii\db\Connection
openFromPoolSequentially() Opens the connection to a server in the pool. yii\db\Connection

Events

隐藏继承的事件

事件类型描述被定义在
EVENT_AFTER_OPEN \yii\db\yii\base\Event An event that is triggered after a DB connection is established yii\db\Connection
EVENT_BEGIN_TRANSACTION \yii\db\yii\base\Event An event that is triggered right before a top-level transaction is started yii\db\Connection
EVENT_COMMIT_TRANSACTION \yii\db\yii\base\Event An event that is triggered right after a top-level transaction is committed yii\db\Connection
EVENT_ROLLBACK_TRANSACTION \yii\db\yii\base\Event An event that is triggered right after a top-level transaction is rolled back yii\db\Connection

属性详情

$attributes 公共 属性

PDO attributes (name => value) that should be set when calling open() to establish a DB connection. Please refer to the PHP manual for details about available attributes.

public array $attributes null
$charset 公共 属性

The charset used for database connection. The property is only used for MySQL, PostgreSQL and CUBRID databases. Defaults to null, meaning using default charset as configured by the database.

For Oracle Database, the charset must be specified in the $dsn, for example for UTF-8 by appending ;charset=UTF-8 to the DSN string.

The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify charset via $dsn like 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'.

public string $charset null
$commandClass 公共 属性 (自版本 2.0.7 可用)
Deprecated since 2.0.14. Use $commandMap for precise configuration.

The class used to create new database yii\db\Command objects. If you want to extend the yii\db\Command class, you may configure this property to use your extended version of the class. Since version 2.0.14 $commandMap is used if this property is set to its default value.

参见 createCommand().

public string $commandClass 'yii\db\Command'
$commandMap 公共 属性 (自版本 2.0.14 可用)

Mapping between PDO driver names and yii\db\Command classes. The keys of the array are PDO driver names while the values are either the corresponding command class names or configurations. Please refer to Yii::createObject() for details on how to specify a configuration.

This property is mainly used by createCommand() to create new database yii\db\Command objects. You normally do not need to set this property unless you want to use your own yii\db\Command class or support DBMS that is not supported by Yii.

public array $commandMap = ['pgsql' => 'yii\db\Command''mysqli' => 'yii\db\Command''mysql' => 'yii\db\Command''sqlite' => 'yii\db\sqlite\Command''sqlite2' => 'yii\db\sqlite\Command''sqlsrv' => 'yii\db\Command''oci' => 'yii\db\Command''mssql' => 'yii\db\Command''dblib' => 'yii\db\Command''cubrid' => 'yii\db\Command']
$driverName 公共 属性

Name of the DB driver

public string getDriverName ( )
public void setDriverName ( $driverName )
$dsn 公共 属性

The Data Source Name, or DSN, contains the information required to connect to the database. Please refer to the PHP manual on the format of the DSN string.

For SQLite you may use a path alias for specifying the database path, e.g. sqlite:@app/data/db.sql.

参见 $charset.

public string $dsn null
$emulatePrepare 公共 属性

Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare support to bypass the buggy native prepare support. The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.

public boolean $emulatePrepare null
$enableLogging 公共 属性 (自版本 2.0.12 可用)

Whether to enable logging of database queries. Defaults to true. You may want to disable this option in a production environment to gain performance if you do not need the information being logged.

参见 $enableProfiling.

public boolean $enableLogging true
$enableProfiling 公共 属性 (自版本 2.0.12 可用)

Whether to enable profiling of opening database connection and database queries. Defaults to true. You may want to disable this option in a production environment to gain performance if you do not need the information being logged.

参见 $enableLogging.

public boolean $enableProfiling true
$enableQueryCache 公共 属性

Whether to enable query caching. Note that in order to enable query caching, a valid cache component as specified by $queryCache must be enabled and $enableQueryCache must be set true. Also, only the results of the queries enclosed within cache() will be cached.

参见:

public boolean $enableQueryCache true
$enableSavepoint 公共 属性

Whether to enable savepoint. Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.

public boolean $enableSavepoint true
$enableSchemaCache 公共 属性

Whether to enable schema caching. Note that in order to enable truly schema caching, a valid cache component as specified by $schemaCache must be enabled and $enableSchemaCache must be set true.

参见:

public boolean $enableSchemaCache false
$enableSlaves 公共 属性

Whether to enable read/write splitting by using $slaves to read data. Note that if $slaves is empty, read/write splitting will NOT be enabled no matter what value this property takes.

public boolean $enableSlaves true
$isActive 公共 只读 属性

Whether the DB connection is established

public boolean getIsActive ( )
$lastInsertID 公共 只读 属性

The row ID of the last row inserted, or the last value retrieved from the sequence object

public string getLastInsertID ( $sequenceName '' )
$master 公共 只读 属性

The currently active master connection. null is returned if there is no master available.

$masterConfig 公共 属性

The configuration that should be merged with every master configuration listed in $masters. For example,

[
    'username' => 'master',
    'password' => 'master',
    'attributes' => [
        // use a smaller connection timeout
        PDO::ATTR_TIMEOUT => 10,
    ],
]
public array $masterConfig = []
$masterPdo 公共 只读 属性

The PDO instance for the currently active master connection.

public PDO getMasterPdo ( )
$masters 公共 属性

List of master connection configurations. Each configuration is used to create a master DB connection. When open() is called, one of these configurations will be chosen and used to create a DB connection which will be used by this object. Note that when this property is not empty, the connection setting (e.g. "dsn", "username") of this object will be ignored.

参见:

public array $masters = []
$password 公共 属性

The password for establishing DB connection. Defaults to null meaning no password to use.

public string $password null
$pdo 公共 属性

The PHP PDO instance associated with this DB connection. This property is mainly managed by open() and close() methods. When a DB connection is active, this property will represent a PDO instance; otherwise, it will be null.

参见 $pdoClass.

public PDO $pdo null
$pdoClass 公共 属性

Custom PDO wrapper class. If not set, it will use PDO or yii\db\mssql\PDO when MSSQL is used.

参见 $pdo.

public string $pdoClass null
$queryBuilder 公共 属性

The query builder for the current DB connection.

public yii\db\QueryBuilder getQueryBuilder ( )
public void setQueryBuilder ( $value )
$queryCache 公共 属性

The cache object or the ID of the cache application component that is used for query caching.

参见 $enableQueryCache.

$queryCacheDuration 公共 属性

The default number of seconds that query results can remain valid in cache. Defaults to 3600, meaning 3600 seconds, or one hour. Use 0 to indicate that the cached data will never expire. The value of this property will be used when cache() is called without a cache duration.

参见:

$schema 公共 只读 属性

The schema information for the database opened by this connection.

$schemaCache 公共 属性

The cache object or the ID of the cache application component that is used to cache the table metadata.

参见 $enableSchemaCache.

$schemaCacheDuration 公共 属性

Number of seconds that table metadata can remain valid in cache. Use 0 to indicate that the cached data will never expire.

参见 $enableSchemaCache.

$schemaCacheExclude 公共 属性

List of tables whose metadata should NOT be cached. Defaults to empty array. The table names may contain schema prefix, if any. Do not quote the table names.

参见 $enableSchemaCache.

$schemaMap 公共 属性

Mapping between PDO driver names and yii\db\Schema classes. The keys of the array are PDO driver names while the values are either the corresponding schema class names or configurations. Please refer to Yii::createObject() for details on how to specify a configuration.

This property is mainly used by getSchema() when fetching the database schema information. You normally do not need to set this property unless you want to use your own yii\db\Schema class to support DBMS that is not supported by Yii.

public array $schemaMap = ['pgsql' => 'yii\db\pgsql\Schema''mysqli' => 'yii\db\mysql\Schema''mysql' => 'yii\db\mysql\Schema''sqlite' => 'yii\db\sqlite\Schema''sqlite2' => 'yii\db\sqlite\Schema''sqlsrv' => 'yii\db\mssql\Schema''oci' => 'yii\db\oci\Schema''mssql' => 'yii\db\mssql\Schema''dblib' => 'yii\db\mssql\Schema''cubrid' => 'yii\db\cubrid\Schema']
$serverRetryInterval 公共 属性

The retry interval in seconds for dead servers listed in $masters and $slaves. This is used together with $serverStatusCache.

$serverStatusCache 公共 属性

The cache object or the ID of the cache application component that is used to store the health status of the DB servers specified in $masters and $slaves. This is used only when read/write splitting is enabled or $masters is not empty. Set boolean false to disabled server status caching.

$serverVersion 公共 只读 属性

Server version as a string.

$shuffleMasters 公共 属性 (自版本 2.0.11 可用)

Whether to shuffle $masters before getting one.

参见 $masters.

public boolean $shuffleMasters true
$slave 公共 只读 属性

The currently active slave connection. null is returned if there is no slave available and $fallbackToMaster is false.

public yii\db\Connection getSlave ( $fallbackToMaster true )
$slaveConfig 公共 属性

The configuration that should be merged with every slave configuration listed in $slaves. For example,

[
    'username' => 'slave',
    'password' => 'slave',
    'attributes' => [
        // use a smaller connection timeout
        PDO::ATTR_TIMEOUT => 10,
    ],
]
public array $slaveConfig = []
$slavePdo 公共 只读 属性

The PDO instance for the currently active slave connection. null is returned if no slave connection is available and $fallbackToMaster is false.

public PDO getSlavePdo ( $fallbackToMaster true )
$slaves 公共 属性

List of slave connection configurations. Each configuration is used to create a slave DB connection. When $enableSlaves is true, one of these configurations will be chosen and used to create a DB connection for performing read queries only.

参见:

public array $slaves = []
$tablePrefix 公共 属性

The common prefix or suffix for table names. If a table name is given as {{%TableName}}, then the percentage character % will be replaced with this property value. For example, {{%post}} becomes {{tbl_post}}.

public string $tablePrefix ''
$transaction 公共 只读 属性

The currently active transaction. Null if no active transaction.

$username 公共 属性

The username for establishing DB connection. Defaults to null meaning no username to use.

public string $username null

方法详情

__clone() 公共 方法

Reset the connection after cloning.

public void __clone()
__sleep() 公共 方法

Close the connection before serializing.

public array __sleep()
beginTransaction() 公共 方法

Starts a transaction.

public yii\db\Transaction beginTransaction($isolationLevel null)
$isolationLevel string|null

The isolation level to use for this transaction. See yii\db\Transaction::begin() for details.

return yii\db\Transaction

The transaction initiated

cache() 公共 方法

Uses query cache for the queries performed with the callable.

When query caching is enabled ($enableQueryCache is true and $queryCache refers to a valid cache), queries performed within the callable will be cached and their results will be fetched from cache if available. For example,

// The customer will be fetched from cache if available.
// If not, the query will be made against DB and cached for use next time.
$customer = $db->cache(function (Connection $db) {
    return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
});

Note that query cache is only meaningful for queries that return results. For queries performed with yii\db\Command::execute(), query cache will not be used.

参见:

public mixed cache(callable $callable, $duration null, $dependency null)
$callable callable

A PHP callable that contains DB queries which will make use of query cache. The signature of the callable is function (Connection $db).

$duration integer

The number of seconds that query results can remain valid in the cache. If this is not set, the value of $queryCacheDuration will be used instead. Use 0 to indicate that the cached data will never expire.

$dependency yii\caching\Dependency

The cache dependency associated with the cached query results.

return mixed

The return result of the callable

throws \Exception|\Throwable

if there is any exception during query

close() 公共 方法

Closes the currently active DB connection.

It does nothing if the connection is already closed.

public void close()
createCommand() 公共 方法

Creates a command for execution.

public yii\db\Command createCommand($sql null, $params = [])
$sql string

The SQL statement to be executed

$params array

The parameters to be bound to the SQL statement

return yii\db\Command

The DB command

createPdoInstance() 受保护 方法

Creates the PDO instance.

This method is called by open() to establish a DB connection. The default implementation will create a PHP PDO instance. You may override this method if the default PDO needs to be adapted for certain DBMS.

protected PDO createPdoInstance()
return PDO

The pdo instance

getDriverName() 公共 方法

Returns the name of the DB driver. Based on the the current $dsn, in case it was not set explicitly by an end user.

public string getDriverName()
return string

Name of the DB driver

getIsActive() 公共 方法

Returns a value indicating whether the DB connection is established.

public boolean getIsActive()
return boolean

Whether the DB connection is established

getLastInsertID() 公共 方法

Returns the ID of the last inserted row or sequence value.

参见 http://php.net/manual/en/pdo.lastinsertid.php.

public string getLastInsertID($sequenceName '')
$sequenceName string

Name of the sequence object (required by some DBMS)

return string

The row ID of the last row inserted, or the last value retrieved from the sequence object

getMaster() 公共 方法 (自版本 2.0.11 可用)

Returns the currently active master connection.

If this method is called for the first time, it will try to open a master connection.

public yii\db\Connection getMaster()
return yii\db\Connection

The currently active master connection. null is returned if there is no master available.

getMasterPdo() 公共 方法

Returns the PDO instance for the currently active master connection.

This method will open the master DB connection and then return $pdo.

public PDO getMasterPdo()
return PDO

The PDO instance for the currently active master connection.

getQueryBuilder() 公共 方法

Returns the query builder for the current DB connection.

public yii\db\QueryBuilder getQueryBuilder()
return yii\db\QueryBuilder

The query builder for the current DB connection.

getQueryCacheInfo() 公共 方法

Returns the current query cache information.

This method is used internally by yii\db\Command.

public array getQueryCacheInfo($duration, $dependency)
$duration integer

The preferred caching duration. If null, it will be ignored.

$dependency yii\caching\Dependency

The preferred caching dependency. If null, it will be ignored.

return array

The current query cache information, or null if query cache is not enabled.

getSchema() 公共 方法

Returns the schema information for the database opened by this connection.

public yii\db\Schema getSchema()
return yii\db\Schema

The schema information for the database opened by this connection.

throws yii\base\NotSupportedException

if there is no support for the current driver type

getServerVersion() 公共 方法 (自版本 2.0.14 可用)

Returns a server version as a string comparable by \version_compare().

public string getServerVersion()
return string

Server version as a string.

getSlave() 公共 方法

Returns the currently active slave connection.

If this method is called for the first time, it will try to open a slave connection when $enableSlaves is true.

public yii\db\Connection getSlave($fallbackToMaster true)
$fallbackToMaster boolean

Whether to return a master connection in case there is no slave connection available.

return yii\db\Connection

The currently active slave connection. null is returned if there is no slave available and $fallbackToMaster is false.

getSlavePdo() 公共 方法

Returns the PDO instance for the currently active slave connection.

When $enableSlaves is true, one of the slaves will be used for read queries, and its PDO instance will be returned by this method.

public PDO getSlavePdo($fallbackToMaster true)
$fallbackToMaster boolean

Whether to return a master PDO in case none of the slave connections is available.

return PDO

The PDO instance for the currently active slave connection. null is returned if no slave connection is available and $fallbackToMaster is false.

getTableSchema() 公共 方法

Obtains the schema information for the named table.

public yii\db\TableSchema getTableSchema($name, $refresh false)
$name string

Table name.

$refresh boolean

Whether to reload the table schema even if it is found in the cache.

return yii\db\TableSchema

Table schema information. Null if the named table does not exist.

getTransaction() 公共 方法

Returns the currently active transaction.

public yii\db\Transaction|null getTransaction()
return yii\db\Transaction|null

The currently active transaction. Null if no active transaction.

initConnection() 受保护 方法

Initializes the DB connection.

This method is invoked right after the DB connection is established. The default implementation turns on PDO::ATTR_EMULATE_PREPARES if $emulatePrepare is true, and sets the database $charset if it is not empty. It then triggers an EVENT_AFTER_OPEN event.

protected void initConnection()
noCache() 公共 方法

Disables query cache temporarily.

Queries performed within the callable will not use query cache at all. For example,

$db->cache(function (Connection $db) {

    // ... queries that use query cache ...

    return $db->noCache(function (Connection $db) {
        // this query will not use query cache
        return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
    });
});

参见:

public mixed noCache(callable $callable)
$callable callable

A PHP callable that contains DB queries which should not use query cache. The signature of the callable is function (Connection $db).

return mixed

The return result of the callable

throws \Exception|\Throwable

if there is any exception during query

open() 公共 方法

Establishes a DB connection.

It does nothing if a DB connection has already been established.

public void open()
throws yii\db\Exception

if connection fails

openFromPool() 受保护 方法

Opens the connection to a server in the pool.

This method implements the load balancing among the given list of the servers. Connections will be tried in random order.

protected yii\db\Connection openFromPool(array $pool, array $sharedConfig)
$pool array

The list of connection configurations in the server pool

$sharedConfig array

The configuration common to those given in $pool.

return yii\db\Connection

The opened DB connection, or null if no server is available

throws yii\base\InvalidConfigException

if a configuration does not specify "dsn"

openFromPoolSequentially() 受保护 方法 (自版本 2.0.11 可用)

Opens the connection to a server in the pool.

This method implements the load balancing among the given list of the servers. Connections will be tried in sequential order.

protected yii\db\Connection openFromPoolSequentially(array $pool, array $sharedConfig)
$pool array

The list of connection configurations in the server pool

$sharedConfig array

The configuration common to those given in $pool.

return yii\db\Connection

The opened DB connection, or null if no server is available

throws yii\base\InvalidConfigException

if a configuration does not specify "dsn"

quoteColumnName() 公共 方法

Quotes a column name for use in a query.

If the column name contains prefix, the prefix will also be properly quoted. If the column name is already quoted or contains special characters including '(', '[[' and '{{', then this method will do nothing.

public string quoteColumnName($name)
$name string

Column name

return string

The properly quoted column name

quoteSql() 公共 方法

Processes a SQL statement by quoting table and column names that are enclosed within double brackets.

Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the beginning or ending of a table name will be replaced with $tablePrefix.

public string quoteSql($sql)
$sql string

The SQL to be quoted

return string

The quoted SQL

quoteTableName() 公共 方法

Quotes a table name for use in a query.

If the table name contains schema prefix, the prefix will also be properly quoted. If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method will do nothing.

public string quoteTableName($name)
$name string

Table name

return string

The properly quoted table name

quoteValue() 公共 方法

Quotes a string value for use in a query.

Note that if the parameter is not a string, it will be returned without change.

参见 http://php.net/manual/en/pdo.quote.php.

public string quoteValue($value)
$value string

String to be quoted

return string

The properly quoted string

setDriverName() 公共 方法

Changes the current driver name.

public void setDriverName($driverName)
$driverName string

Name of the DB driver

setQueryBuilder() 公共 方法 (自版本 2.0.14 可用)

Can be used to set yii\db\QueryBuilder configuration via Connection configuration array.

public void setQueryBuilder($value)
$value array

The yii\db\QueryBuilder properties to be configured.

transaction() 公共 方法

Executes callback provided in a transaction.

public mixed transaction(callable $callback, $isolationLevel null)
$callback callable

A valid PHP callback that performs the job. Accepts connection instance as parameter.

$isolationLevel string|null

The isolation level to use for this transaction. See yii\db\Transaction::begin() for details.

return mixed

Result of callback function

throws \Exception|\Throwable

if there is any exception during query. In this case the transaction will be rolled back.

useMaster() 公共 方法

Executes the provided callback by using the master connection.

This method is provided so that you can temporarily force using the master connection to perform DB operations even if they are read queries. For example,

$result = $db->useMaster(function ($db) {
    return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
});
public mixed useMaster(callable $callback)
$callback callable

A PHP callable to be executed by this method. Its signature is function (Connection $db). Its return value will be returned by this method.

return mixed

The return value of the callback

throws \Exception|\Throwable

if there is any exception thrown from the callback

事件详情

EVENT_AFTER_OPEN event of type \yii\db\yii\base\Event

An event that is triggered after a DB connection is established

EVENT_BEGIN_TRANSACTION event of type \yii\db\yii\base\Event

An event that is triggered right before a top-level transaction is started

EVENT_COMMIT_TRANSACTION event of type \yii\db\yii\base\Event

An event that is triggered right after a top-level transaction is committed

EVENT_ROLLBACK_TRANSACTION event of type \yii\db\yii\base\Event

An event that is triggered right after a top-level transaction is rolled back