# Connection

> Connection represents a connection to a database via [PDO](https://www.php.net/manual/en/book.pdo.php).

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [db](/docs/api/yii/db/index.md) › Connection

| class | `yii\db\Connection` |
| --- | --- |
| Extends | [`yii\base\Component`](/docs/api/yii/base/component/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0 |
| Source | [`framework/db/Connection.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/db/Connection.php#L148) |

Connection represents a connection to a database via [PDO](https://www.php.net/manual/en/book.pdo.php).

Connection works together with [`Command`](/docs/api/yii/db/command/index.md), [`DataReader`](/docs/api/yii/db/datareader/index.md) and [`Transaction`](/docs/api/yii/db/transaction/index.md)
to provide data access to various DBMS in a common set of APIs. They are a thin wrapper
of the [PDO PHP extension](https://www.php.net/manual/en/book.pdo.php).

Connection supports database replication and read-write splitting. In particular, a Connection component
can be configured with multiple [`$masters`](/docs/api/yii/db/connection/index.md#property-masters) and [`$slaves`](/docs/api/yii/db/connection/index.md#property-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`](/docs/api/yii/db/connection/index.md#property-dsn), [`$username`](/docs/api/yii/db/connection/index.md#property-username) and [`$password`](/docs/api/yii/db/connection/index.md#property-password), and then
call [`open()`](/docs/api/yii/db/connection/index.md#method-open) to connect to the database server. The current state of the connection can be checked using [`$isActive`](/docs/api/yii/db/connection/index.md#property-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 [`Command`](/docs/api/yii/db/command/index.md).

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' => 'utf8mb4',
    ],
],
```

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| [`$attributes`](#property-attributes) | `array` | PDO attributes (name => value) that should be set when calling [`open()`](/docs/api/yii/db/connection/index.md#method-open) to establish a DB connection. Default: `null`. | `Connection` |
| <span id="property-behaviors"></span>[`$behaviors`](/docs/api/yii/base/component/index.md#property-behaviors) read-only | `array<`[`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md)`<static>>` | List of behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`$charset`](#property-charset) | `string\|null` | The charset used for database connection. Default: `null`. | `Connection` |
| [`$commandMap`](#property-commandMap) | `array` | Mapping between PDO driver names and [`Command`](/docs/api/yii/db/command/index.md) classes. Default: `['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\mssql\Command', 'oci' => 'yii\db\oci\Command', 'mssql' => 'yii\db\mssql\Command', 'dblib' => 'yii\db\mssql\Command']`. Available since 2.0.14. | `Connection` |
| <span id="property-driverName"></span>`$driverName` | `string` | Name of the DB driver. | `Connection` |
| [`$dsn`](#property-dsn) | `string` | The Data Source Name, or DSN, contains the information required to connect to the database. Default: `null`. | `Connection` |
| <span id="property-effectiveCharset"></span>`$effectiveCharset` read-only | `string\|null` | The effective connection charset, or `null` when the connection relies on the database server defaults. | `Connection` |
| [`$emulatePrepare`](#property-emulatePrepare) | `bool\|null` | Whether to turn on prepare emulation. Default: `null`. | `Connection` |
| [`$enableLogging`](#property-enableLogging) | `bool` | Whether to enable logging of database queries. Default: `true`. Available since 2.0.12. | `Connection` |
| [`$enableProfiling`](#property-enableProfiling) | `bool` | Whether to enable profiling of opening database connection and database queries. Default: `true`. Available since 2.0.12. | `Connection` |
| [`$enableQueryCache`](#property-enableQueryCache) | `bool` | Whether to enable query caching. Default: `true`. | `Connection` |
| [`$enableSavepoint`](#property-enableSavepoint) | `bool` | Whether to enable [savepoint](https://en.wikipedia.org/wiki/Savepoint). Default: `true`. | `Connection` |
| [`$enableSchemaCache`](#property-enableSchemaCache) | `bool` | Whether to enable schema caching. Default: `false`. | `Connection` |
| [`$enableSlaves`](#property-enableSlaves) | `bool` | Whether to enable read/write splitting by using [`$slaves`](/docs/api/yii/db/connection/index.md#property-slaves) to read data. Default: `true`. | `Connection` |
| <span id="property-isActive"></span>`$isActive` read-only | `bool` | Whether the DB connection is established. | `Connection` |
| <span id="property-isSybase"></span>`$isSybase` | `bool` | If the database connected via pdo_dblib is SyBase. Default: `false`. Available since 2.0.38. | `Connection` |
| <span id="property-lastInsertID"></span>`$lastInsertID` read-only | `string` | The row ID of the last row inserted, or the last value retrieved from the sequence object. | `Connection` |
| <span id="property-master"></span>`$master` read-only | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The currently active master connection. `null` is returned if there is no master available. | `Connection` |
| [`$masterConfig`](#property-masterConfig) | `array` | The configuration that should be merged with every master configuration listed in [`$masters`](/docs/api/yii/db/connection/index.md#property-masters). Default: `[]`. | `Connection` |
| <span id="property-masterPdo"></span>`$masterPdo` read-only | [`PDO`](https://www.php.net/manual/en/class.pdo.php) | The PDO instance for the currently active master connection. | `Connection` |
| [`$masters`](#property-masters) | `array` | List of master connection configurations. Default: `[]`. | `Connection` |
| [`$password`](#property-password) | `string\|null` | The password for establishing DB connection. Default: `null`. | `Connection` |
| [`$pdo`](#property-pdo) | [`PDO`](https://www.php.net/manual/en/class.pdo.php)`\|null` | The PHP PDO instance associated with this DB connection. Default: `null`. | `Connection` |
| [`$pdoClass`](#property-pdoClass) | `string\|null` | Custom PDO wrapper class. Default: `null`. | `Connection` |
| <span id="property-queryBuilder"></span>`$queryBuilder` | `array` | The [`QueryBuilder`](/docs/api/yii/db/querybuilder/index.md) properties to be configured. | `Connection` |
| <span id="property-queryCache"></span>`$queryCache` | [`yii\caching\CacheInterface`](/docs/api/yii/caching/cacheinterface/index.md)`\|string` | The cache object or the ID of the cache application component that is used for query caching. Default: `'cache'`. | `Connection` |
| [`$queryCacheDuration`](#property-queryCacheDuration) | `int` | The default number of seconds that query results can remain valid in cache. Default: `3600`. | `Connection` |
| <span id="property-schema"></span>`$schema` read-only | `yii\db\TSchema` | The schema information for the database opened by this connection. | `Connection` |
| <span id="property-schemaCache"></span>`$schemaCache` | [`yii\caching\CacheInterface`](/docs/api/yii/caching/cacheinterface/index.md)`\|string` | The cache object or the ID of the cache application component that is used to cache the table metadata. Default: `'cache'`. | `Connection` |
| [`$schemaCacheDuration`](#property-schemaCacheDuration) | `int` | Number of seconds that table metadata can remain valid in cache. Default: `3600`. | `Connection` |
| [`$schemaCacheExclude`](#property-schemaCacheExclude) | `array` | List of tables whose metadata should NOT be cached. Default: `[]`. | `Connection` |
| [`$schemaMap`](#property-schemaMap) | `array` | Mapping between PDO driver names and [`Schema`](/docs/api/yii/db/schema/index.md) classes. Default: `['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']`. | `Connection` |
| [`$serverRetryInterval`](#property-serverRetryInterval) | `int` | The retry interval in seconds for dead servers listed in [`$masters`](/docs/api/yii/db/connection/index.md#property-masters) and [`$slaves`](/docs/api/yii/db/connection/index.md#property-slaves). Default: `600`. | `Connection` |
| [`$serverStatusCache`](#property-serverStatusCache) | [`yii\caching\CacheInterface`](/docs/api/yii/caching/cacheinterface/index.md)`\|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`](/docs/api/yii/db/connection/index.md#property-masters) and [`$slaves`](/docs/api/yii/db/connection/index.md#property-slaves). Default: `'cache'`. | `Connection` |
| <span id="property-serverVersion"></span>`$serverVersion` read-only | `string` | Server version as a string. | `Connection` |
| <span id="property-shuffleMasters"></span>`$shuffleMasters` | `bool` | Whether to shuffle [`$masters`](/docs/api/yii/db/connection/index.md#property-masters) before getting one. Default: `true`. Available since 2.0.11. | `Connection` |
| <span id="property-slave"></span>`$slave` read-only | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The currently active slave connection. `null` is returned if there is no slave available and `$fallbackToMaster` is false. | `Connection` |
| [`$slaveConfig`](#property-slaveConfig) | `array` | The configuration that should be merged with every slave configuration listed in [`$slaves`](/docs/api/yii/db/connection/index.md#property-slaves). Default: `[]`. | `Connection` |
| <span id="property-slavePdo"></span>`$slavePdo` read-only | [`PDO`](https://www.php.net/manual/en/class.pdo.php)`\|null` | The PDO instance for the currently active slave connection. `null` is returned if no slave connection is available and `$fallbackToMaster` is false. | `Connection` |
| [`$slaves`](#property-slaves) | `array` | List of slave connection configurations. Default: `[]`. | `Connection` |
| [`$tablePrefix`](#property-tablePrefix) | `string` | The common prefix or suffix for table names. Default: `''`. | `Connection` |
| [`$transaction`](#property-transaction) read-only | [`Transaction`](/docs/api/yii/db/transaction/index.md)`\|null` | The currently active transaction. | `Connection` |
| [`$transactionMap`](#property-transactionMap) | `array<string, class-string<`[`Transaction`](/docs/api/yii/db/transaction/index.md)`>\|array<string, mixed>>` | Mapping between PDO driver names and [`Transaction`](/docs/api/yii/db/transaction/index.md) classes or configurations. Default: `['pgsql' => \yii\db\pgsql\Transaction::class, 'mysqli' => \yii\db\Transaction::class, 'mysql' => \yii\db\Transaction::class, 'sqlite' => \yii\db\Transaction::class, 'sqlite2' => \yii\db\Transaction::class, 'sqlsrv' => \yii\db\Transaction::class, 'oci' => \yii\db\Transaction::class, 'mssql' => \yii\db\Transaction::class, 'dblib' => \yii\db\Transaction::class]`. Available since 22.0. | `Connection` |
| [`$username`](#property-username) | `string\|null` | The username for establishing DB connection. Default: `null`. | `Connection` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/component/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`__clone()`](#method-__clone) | Reset the connection after cloning. | `Connection` |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/component/index.md#method-__get) | Returns the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/component/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/component/index.md#method-__set) | Sets the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`__sleep()`](#method-__sleep) | Close the connection before serializing. | `Connection` |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/component/index.md#method-__unset) | Sets a component property to be null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehavior"></span>[`attachBehavior()`](/docs/api/yii/base/component/index.md#method-attachBehavior) | Attaches a behavior to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehaviors"></span>[`attachBehaviors()`](/docs/api/yii/base/component/index.md#method-attachBehaviors) | Attaches a list of behaviors to the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`beginTransaction()`](#method-beginTransaction) | Starts a transaction. | `Connection` |
| <span id="method-behaviors"></span>[`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) | Returns a list of behaviors that this component should behave as. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`cache()`](#method-cache) | Uses query cache for the queries performed with the callable. | `Connection` |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/component/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/component/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`close()`](#method-close) | Closes the currently active DB connection. | `Connection` |
| [`createCommand()`](#method-createCommand) | Creates a command for execution. | `Connection` |
| <span id="method-detachBehavior"></span>[`detachBehavior()`](/docs/api/yii/base/component/index.md#method-detachBehavior) | Detaches a behavior from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-detachBehaviors"></span>[`detachBehaviors()`](/docs/api/yii/base/component/index.md#method-detachBehaviors) | Detaches all behaviors from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-ensureBehaviors"></span>[`ensureBehaviors()`](/docs/api/yii/base/component/index.md#method-ensureBehaviors) | Makes sure that the behaviors declared in [`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) are attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehavior"></span>[`getBehavior()`](/docs/api/yii/base/component/index.md#method-getBehavior) | Returns the named behavior object. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehaviors"></span>[`getBehaviors()`](/docs/api/yii/base/component/index.md#method-getBehaviors) | Returns all behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`getDriverName()`](#method-getDriverName) | Returns the name of the DB driver. Based on the the current [`$dsn`](/docs/api/yii/db/connection/index.md#property-dsn), in case it was not set explicitly by an end user. | `Connection` |
| [`getEffectiveCharset()`](#method-getEffectiveCharset) | Returns the charset the connection effectively uses. | `Connection` |
| [`getIsActive()`](#method-getIsActive) | Returns a value indicating whether the DB connection is established. | `Connection` |
| [`getLastInsertID()`](#method-getLastInsertID) | Returns the ID of the last inserted row or sequence value. | `Connection` |
| [`getMaster()`](#method-getMaster) | Returns the currently active master connection. | `Connection` |
| [`getMasterPdo()`](#method-getMasterPdo) | Returns the PDO instance for the currently active master connection. | `Connection` |
| [`getQueryBuilder()`](#method-getQueryBuilder) | Returns the query builder for the current DB connection. | `Connection` |
| [`getSchema()`](#method-getSchema) | Returns the schema information for the database opened by this connection. | `Connection` |
| [`getServerVersion()`](#method-getServerVersion) | Returns a server version as a string comparable by [`version_compare()`](https://www.php.net/manual/en/function.version-compare.php). | `Connection` |
| [`getSlave()`](#method-getSlave) | Returns the currently active slave connection. | `Connection` |
| [`getSlavePdo()`](#method-getSlavePdo) | Returns the PDO instance for the currently active slave connection. | `Connection` |
| [`getTableSchema()`](#method-getTableSchema) | Obtains the schema information for the named table. | `Connection` |
| [`getTransaction()`](#method-getTransaction) | Returns the currently active transaction. | `Connection` |
| <span id="method-hasEventHandlers"></span>[`hasEventHandlers()`](/docs/api/yii/base/component/index.md#method-hasEventHandlers) | Returns a value indicating whether there is any handler attached to the named event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/component/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/component/index.md#method-hasProperty) | Returns a value indicating whether a property is defined for this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-init"></span>[`init()`](/docs/api/yii/base/baseobject/index.md#method-init) | Initializes the object. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`noCache()`](#method-noCache) | Disables query cache temporarily. | `Connection` |
| <span id="method-off"></span>[`off()`](/docs/api/yii/base/component/index.md#method-off) | Detaches an existing event handler from this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-on"></span>[`on()`](/docs/api/yii/base/component/index.md#method-on) | Attaches an event handler to an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`open()`](#method-open) | Establishes a DB connection. | `Connection` |
| [`quoteColumnName()`](#method-quoteColumnName) | Quotes a column name for use in a query. | `Connection` |
| [`quoteSql()`](#method-quoteSql) | Processes a SQL statement by quoting table and column names that are enclosed within double brackets. | `Connection` |
| [`quoteTableName()`](#method-quoteTableName) | Quotes a table name for use in a query. | `Connection` |
| [`quoteValue()`](#method-quoteValue) | Quotes a string value for use in a query. | `Connection` |
| [`setDriverName()`](#method-setDriverName) | Changes the current driver name. | `Connection` |
| [`setQueryBuilder()`](#method-setQueryBuilder) | Can be used to set [`QueryBuilder`](/docs/api/yii/db/querybuilder/index.md) configuration via Connection configuration array. | `Connection` |
| [`transaction()`](#method-transaction) | Executes callback provided in a transaction. | `Connection` |
| <span id="method-trigger"></span>[`trigger()`](/docs/api/yii/base/component/index.md#method-trigger) | Triggers an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`useMaster()`](#method-useMaster) | Executes the provided callback by using the master connection. | `Connection` |
| [`createPdoInstance()`](#method-createPdoInstance) protected | Creates the PDO instance. | `Connection` |
| [`initConnection()`](#method-initConnection) protected | Initializes the DB connection. | `Connection` |
| [`openFromPool()`](#method-openFromPool) protected | Opens the connection to a server in the pool. | `Connection` |
| [`openFromPoolSequentially()`](#method-openFromPoolSequentially) protected | Opens the connection to a server in the pool. | `Connection` |

## Events

| Event | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="event-EVENT_AFTER_OPEN"></span>`EVENT_AFTER_OPEN` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | An event that is triggered after a DB connection is established Event name: `'afterOpen'`. | `Connection` |
| <span id="event-EVENT_BEGIN_TRANSACTION"></span>`EVENT_BEGIN_TRANSACTION` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | An event that is triggered right before a top-level transaction is started Event name: `'beginTransaction'`. | `Connection` |
| <span id="event-EVENT_COMMIT_TRANSACTION"></span>`EVENT_COMMIT_TRANSACTION` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | An event that is triggered right after a top-level transaction is committed Event name: `'commitTransaction'`. | `Connection` |
| <span id="event-EVENT_ROLLBACK_TRANSACTION"></span>`EVENT_ROLLBACK_TRANSACTION` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | An event that is triggered right after a top-level transaction is rolled back Event name: `'rollbackTransaction'`. | `Connection` |

## Property details

### $attributes <span id="property-attributes"></span>

```php
public array $attributes = null
```

PDO attributes (name => value) that should be set when calling [`open()`](/docs/api/yii/db/connection/index.md#method-open) to establish a DB connection.

Please refer to the
[PHP manual](https://www.php.net/manual/en/pdo.setattribute.php) for
details about available attributes.

### $charset <span id="property-charset"></span>

```php
public string|null $charset = null
```

The charset used for database connection.

The property is only used for MySQL and PostgreSQL
databases. Defaults to `null`. MySQL and MariaDB connections use `utf8mb4` when neither this property nor the
[`$dsn`](/docs/api/yii/db/connection/index.md#property-dsn) specifies a charset. PostgreSQL connections use the default charset configured by the database.

For Oracle Database, the charset must be specified in the [`$dsn`](/docs/api/yii/db/connection/index.md#property-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`](/docs/api/yii/db/connection/index.md#property-dsn) like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.

### $commandMap <span id="property-commandMap"></span>

```php
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\mssql\Command', 'oci' => 'yii\db\oci\Command', 'mssql' => 'yii\db\mssql\Command', 'dblib' => 'yii\db\mssql\Command']
```

Mapping between PDO driver names and [`Command`](/docs/api/yii/db/command/index.md) 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()`](/docs/api/yii/baseyii/index.md#method-createObject) for
details on how to specify a configuration.

This property is mainly used by [`createCommand()`](/docs/api/yii/db/connection/index.md#method-createCommand) to create new database [`Command`](/docs/api/yii/db/command/index.md) objects.
You normally do not need to set this property unless you want to use your own
[`Command`](/docs/api/yii/db/command/index.md) class or support DBMS that is not supported by Yii.

**Since**

2.0.14

### $dsn <span id="property-dsn"></span>

```php
public string $dsn = null
```

The Data Source Name, or DSN, contains the information required to connect to the database.

Please refer to the [PHP manual](https://www.php.net/manual/en/pdo.construct.php) on
the format of the DSN string.

For [SQLite](https://www.php.net/manual/en/ref.pdo-sqlite.connection.php) you may use a [path alias](/docs/guide/concept-aliases/index.md)
for specifying the database path, e.g. `sqlite:@app/data/db.sql`.

### $emulatePrepare <span id="property-emulatePrepare"></span>

```php
public bool|null $emulatePrepare = null
```

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.

### $enableLogging <span id="property-enableLogging"></span>

```php
public bool $enableLogging = true
```

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.

**Since**

2.0.12

### $enableProfiling <span id="property-enableProfiling"></span>

```php
public bool $enableProfiling = true
```

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.

**Since**

2.0.12

### $enableQueryCache <span id="property-enableQueryCache"></span>

```php
public bool $enableQueryCache = true
```

Whether to enable query caching.

Note that in order to enable query caching, a valid cache component as specified
by [`$queryCache`](/docs/api/yii/db/connection/index.md#property-queryCache) must be enabled and [`$enableQueryCache`](/docs/api/yii/db/connection/index.md#property-enableQueryCache) must be set true.
Also, only the results of the queries enclosed within [`cache()`](/docs/api/yii/db/connection/index.md#method-cache) will be cached.

### $enableSavepoint <span id="property-enableSavepoint"></span>

```php
public bool $enableSavepoint = true
```

Whether to enable [savepoint](https://en.wikipedia.org/wiki/Savepoint).

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

### $enableSchemaCache <span id="property-enableSchemaCache"></span>

```php
public bool $enableSchemaCache = false
```

Whether to enable schema caching.

Note that in order to enable truly schema caching, a valid cache component as specified
by [`$schemaCache`](/docs/api/yii/db/connection/index.md#property-schemaCache) must be enabled and [`$enableSchemaCache`](/docs/api/yii/db/connection/index.md#property-enableSchemaCache) must be set true.

### $enableSlaves <span id="property-enableSlaves"></span>

```php
public bool $enableSlaves = true
```

Whether to enable read/write splitting by using [`$slaves`](/docs/api/yii/db/connection/index.md#property-slaves) to read data.

Note that if [`$slaves`](/docs/api/yii/db/connection/index.md#property-slaves) is empty, read/write splitting will NOT be enabled no matter what value this property takes.

### $masterConfig <span id="property-masterConfig"></span>

```php
public array $masterConfig = []
```

The configuration that should be merged with every master configuration listed in [`$masters`](/docs/api/yii/db/connection/index.md#property-masters).

For example,

```
[
    'username' => 'master',
    'password' => 'master',
    'attributes' => [
        // use a smaller connection timeout
        PDO::ATTR_TIMEOUT => 10,
    ],
]
```

### $masters <span id="property-masters"></span>

```php
public array $masters = []
```

List of master connection configurations.

Each configuration is used to create a master DB connection.
When [`open()`](/docs/api/yii/db/connection/index.md#method-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.

### $password <span id="property-password"></span>

```php
public string|null $password = null
```

The password for establishing DB connection.

Defaults to `null` meaning no password to use.

### $pdo <span id="property-pdo"></span>

```php
public PDO|null $pdo = null
```

The PHP PDO instance associated with this DB connection.

This property is mainly managed by [`open()`](/docs/api/yii/db/connection/index.md#method-open) and [`close()`](/docs/api/yii/db/connection/index.md#method-close) methods.
When a DB connection is active, this property will represent a PDO instance;
otherwise, it will be null.

### $pdoClass <span id="property-pdoClass"></span>

```php
public string|null $pdoClass = null
```

Custom PDO wrapper class.

If not set, it will use [`PDO`](https://www.php.net/manual/en/class.pdo.php) or [`PDO`](/docs/api/yii/db/mssql/pdo/index.md) when MSSQL is used.

### $queryCacheDuration <span id="property-queryCacheDuration"></span>

```php
public int $queryCacheDuration = 3600
```

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()`](/docs/api/yii/db/connection/index.md#method-cache) is called without a cache duration.

### $schemaCacheDuration <span id="property-schemaCacheDuration"></span>

```php
public int $schemaCacheDuration = 3600
```

Number of seconds that table metadata can remain valid in cache.

Use 0 to indicate that the cached data will never expire.

### $schemaCacheExclude <span id="property-schemaCacheExclude"></span>

```php
public array $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.

### $schemaMap <span id="property-schemaMap"></span>

```php
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']
```

Mapping between PDO driver names and [`Schema`](/docs/api/yii/db/schema/index.md) 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()`](/docs/api/yii/baseyii/index.md#method-createObject) for
details on how to specify a configuration.

This property is mainly used by [`getSchema()`](/docs/api/yii/db/connection/index.md#method-getSchema) when fetching the database schema information.
You normally do not need to set this property unless you want to use your own
[`Schema`](/docs/api/yii/db/schema/index.md) class to support DBMS that is not supported by Yii.

### $serverRetryInterval <span id="property-serverRetryInterval"></span>

```php
public int $serverRetryInterval = 600
```

The retry interval in seconds for dead servers listed in [`$masters`](/docs/api/yii/db/connection/index.md#property-masters) and [`$slaves`](/docs/api/yii/db/connection/index.md#property-slaves).

This is used together with [`$serverStatusCache`](/docs/api/yii/db/connection/index.md#property-serverStatusCache).

### $serverStatusCache <span id="property-serverStatusCache"></span>

```php
public yii\caching\CacheInterface|string|false $serverStatusCache = 'cache'
```

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`](/docs/api/yii/db/connection/index.md#property-masters) and [`$slaves`](/docs/api/yii/db/connection/index.md#property-slaves).

This is used only when read/write splitting is enabled or [`$masters`](/docs/api/yii/db/connection/index.md#property-masters) is not empty.
Set boolean `false` to disabled server status caching.

### $slaveConfig <span id="property-slaveConfig"></span>

```php
public array $slaveConfig = []
```

The configuration that should be merged with every slave configuration listed in [`$slaves`](/docs/api/yii/db/connection/index.md#property-slaves).

For example,

```
[
    'username' => 'slave',
    'password' => 'slave',
    'attributes' => [
        // use a smaller connection timeout
        PDO::ATTR_TIMEOUT => 10,
    ],
]
```

### $slaves <span id="property-slaves"></span>

```php
public array $slaves = []
```

List of slave connection configurations.

Each configuration is used to create a slave DB connection.
When [`$enableSlaves`](/docs/api/yii/db/connection/index.md#property-enableSlaves) is true, one of these configurations will be chosen and used to create a DB connection
for performing read queries only.

### $tablePrefix <span id="property-tablePrefix"></span>

```php
public string $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}}`.

### $transaction <span id="property-transaction"></span>

```php
public yii\db\Transaction|null $transaction
```

The currently active transaction.

Null if no active
transaction.

**Access**

Read-only (virtual property).

### $transactionMap <span id="property-transactionMap"></span>

```php
public array<string, class-string<yii\db\Transaction>|array<string, mixed>> $transactionMap = ['pgsql' => \yii\db\pgsql\Transaction::class, 'mysqli' => \yii\db\Transaction::class, 'mysql' => \yii\db\Transaction::class, 'sqlite' => \yii\db\Transaction::class, 'sqlite2' => \yii\db\Transaction::class, 'sqlsrv' => \yii\db\Transaction::class, 'oci' => \yii\db\Transaction::class, 'mssql' => \yii\db\Transaction::class, 'dblib' => \yii\db\Transaction::class]
```

Mapping between PDO driver names and [`Transaction`](/docs/api/yii/db/transaction/index.md) classes or configurations.

The keys of the array are PDO driver names while the values are either the corresponding transaction class names
or configurations. Please refer to [`Yii::createObject()`](/docs/api/yii/baseyii/index.md#method-createObject) for details on how to specify a configuration.

This property is mainly used by [`beginTransaction()`](/docs/api/yii/db/connection/index.md#method-beginTransaction) to start new database [`Transaction`](/docs/api/yii/db/transaction/index.md) objects.

You normally do not need to set this property unless you want to use your own [`Transaction`](/docs/api/yii/db/transaction/index.md) class or support
DBMS that is not supported by Yii.

**Since**

22.0

### $username <span id="property-username"></span>

```php
public string|null $username = null
```

The username for establishing DB connection.

Defaults to `null` meaning no username to use.

## Method details

### __clone() <span id="method-__clone"></span>

```php
public function __clone(): mixed
```

Reset the connection after cloning.

**Returns**

`mixed`

### __sleep() <span id="method-__sleep"></span>

```php
public function __sleep(): array
```

Close the connection before serializing.

**Returns**

`array`

### beginTransaction() <span id="method-beginTransaction"></span>

```php
public function beginTransaction(string|null $isolationLevel = null): yii\db\Transaction
```

Starts a transaction.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$isolationLevel` | `string\|null` | The isolation level to use for this transaction. See [`Transaction::begin()`](/docs/api/yii/db/transaction/index.md#method-begin) for details. |

**Returns**

[`Transaction`](/docs/api/yii/db/transaction/index.md): The transaction initiated

### cache() <span id="method-cache"></span>

```php
public function cache(callable $callable, int|null $duration = null, yii\caching\Dependency|null $dependency = null): mixed
```

Uses query cache for the queries performed with the callable.

When query caching is enabled ([`$enableQueryCache`](/docs/api/yii/db/connection/index.md#property-enableQueryCache) is true and [`$queryCache`](/docs/api/yii/db/connection/index.md#property-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
[`Command::execute()`](/docs/api/yii/db/command/index.md#method-execute), query cache will not be used.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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` | `int\|null` | The number of seconds that query results can remain valid in the cache. If this is not set, the value of [`$queryCacheDuration`](/docs/api/yii/db/connection/index.md#property-queryCacheDuration) will be used instead. Use 0 to indicate that the cached data will never expire. |
| `$dependency` | [`yii\caching\Dependency`](/docs/api/yii/caching/dependency/index.md)`\|null` | The cache dependency associated with the cached query results. |

**Returns**

`mixed`: The return result of the callable

**Throws**

- [`Throwable`](https://www.php.net/manual/en/class.throwable.php): if there is any exception during query

**See also**

- [`$enableQueryCache`](/docs/api/yii/db/connection/index.md#property-enableQueryCache)
- [`$queryCache`](/docs/api/yii/db/connection/index.md#property-queryCache)
- [`noCache()`](/docs/api/yii/db/connection/index.md#method-noCache)

### close() <span id="method-close"></span>

```php
public function close(): mixed
```

Closes the currently active DB connection.

It does nothing if the connection is already closed.

**Returns**

`mixed`

### createCommand() <span id="method-createCommand"></span>

```php
public function createCommand(string|null $sql = null, array $params = []): yii\db\Command
```

Creates a command for execution.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$sql` | `string\|null` | The SQL statement to be executed |
| `$params` | `array` | The parameters to be bound to the SQL statement |

**Returns**

[`Command`](/docs/api/yii/db/command/index.md): The DB command

### getDriverName() <span id="method-getDriverName"></span>

```php
public function getDriverName(): string|null
```

Returns the name of the DB driver. Based on the the current [`$dsn`](/docs/api/yii/db/connection/index.md#property-dsn), in case it was not set explicitly
by an end user.

**Returns**

`string|null`: Name of the DB driver

### getEffectiveCharset() <span id="method-getEffectiveCharset"></span>

```php
public function getEffectiveCharset(): string|null
```

Returns the charset the connection effectively uses.

Resolution order: [`$charset`](/docs/api/yii/db/connection/index.md#property-charset) when set, then a `charset` element in the [`$dsn`](/docs/api/yii/db/connection/index.md#property-dsn), then `utf8mb4` for MySQL and
MariaDB. The value derives from the configuration only, so it is available before the connection is opened.

**Returns**

`string|null`: The effective connection charset, or `null` when the connection relies on the database server defaults.

**Since**

22.0

### getIsActive() <span id="method-getIsActive"></span>

```php
public function getIsActive(): bool
```

Returns a value indicating whether the DB connection is established.

**Returns**

`bool`: Whether the DB connection is established

### getLastInsertID() <span id="method-getLastInsertID"></span>

```php
public function getLastInsertID(string $sequenceName = ''): string
```

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

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$sequenceName` | `string` | Name of the sequence object (required by some DBMS) |

**Returns**

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

**See also**

- <https://www.php.net/manual/en/pdo.lastinsertid.php>

### getMaster() <span id="method-getMaster"></span>

```php
public function getMaster(): yii\db\Connection|null
```

Returns the currently active master connection.

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

**Returns**

[`Connection`](/docs/api/yii/db/connection/index.md)`|null`: The currently active master connection. `null` is returned if there is no master available.

**Since**

2.0.11

### getMasterPdo() <span id="method-getMasterPdo"></span>

```php
public function getMasterPdo(): PDO
```

Returns the PDO instance for the currently active master connection.

This method will open the master DB connection and then return [`$pdo`](/docs/api/yii/db/connection/index.md#property-pdo).

**Returns**

[`PDO`](https://www.php.net/manual/en/class.pdo.php): The PDO instance for the currently active master connection.

### getQueryBuilder() <span id="method-getQueryBuilder"></span>

```php
public function getQueryBuilder(): yii\db\TQueryBuilder
```

Returns the query builder for the current DB connection.

**Returns**

`yii\db\TQueryBuilder`: The query builder for the current DB connection.

### getSchema() <span id="method-getSchema"></span>

```php
public function getSchema(): yii\db\TSchema
```

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

**Returns**

`yii\db\TSchema`: The schema information for the database opened by this connection.

**Throws**

- [`yii\base\NotSupportedException`](/docs/api/yii/base/notsupportedexception/index.md): if there is no support for the current driver type

### getServerVersion() <span id="method-getServerVersion"></span>

```php
public function getServerVersion(): string
```

Returns a server version as a string comparable by [`version_compare()`](https://www.php.net/manual/en/function.version-compare.php).

**Returns**

`string`: Server version as a string.

**Since**

2.0.14

### getSlave() <span id="method-getSlave"></span>

```php
public function getSlave(bool $fallbackToMaster = true): yii\db\Connection|null
```

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`](/docs/api/yii/db/connection/index.md#property-enableSlaves) is true.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$fallbackToMaster` | `bool` | Whether to return a master connection in case there is no slave connection available. |

**Returns**

[`Connection`](/docs/api/yii/db/connection/index.md)`|null`: The currently active slave connection. `null` is returned if there is no slave available and `$fallbackToMaster` is false.

### getSlavePdo() <span id="method-getSlavePdo"></span>

```php
public function getSlavePdo(bool $fallbackToMaster = true): PDO|null
```

Returns the PDO instance for the currently active slave connection.

When [`$enableSlaves`](/docs/api/yii/db/connection/index.md#property-enableSlaves) is true, one of the slaves will be used for read queries, and its PDO instance
will be returned by this method.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$fallbackToMaster` | `bool` | Whether to return a master PDO in case none of the slave connections is available. |

**Returns**

[`PDO`](https://www.php.net/manual/en/class.pdo.php)`|null`: The PDO instance for the currently active slave connection. `null` is returned if no slave connection is available and `$fallbackToMaster` is false.

### getTableSchema() <span id="method-getTableSchema"></span>

```php
public function getTableSchema(string $name, bool $refresh = false): yii\db\TableSchema|null
```

Obtains the schema information for the named table.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | Table name. |
| `$refresh` | `bool` | Whether to reload the table schema even if it is found in the cache. |

**Returns**

[`TableSchema`](/docs/api/yii/db/tableschema/index.md)`|null`: Table schema information. Null if the named table does not exist.

### getTransaction() <span id="method-getTransaction"></span>

```php
public function getTransaction(): yii\db\Transaction|null
```

Returns the currently active transaction.

**Returns**

[`Transaction`](/docs/api/yii/db/transaction/index.md)`|null`: The currently active transaction. Null if no active transaction.

### noCache() <span id="method-noCache"></span>

```php
public function noCache(callable $callable): mixed
```

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();
    });
});
```

**Parameters**

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

**Returns**

`mixed`: The return result of the callable

**Throws**

- [`Throwable`](https://www.php.net/manual/en/class.throwable.php): if there is any exception during query

**See also**

- [`$enableQueryCache`](/docs/api/yii/db/connection/index.md#property-enableQueryCache)
- [`$queryCache`](/docs/api/yii/db/connection/index.md#property-queryCache)
- [`cache()`](/docs/api/yii/db/connection/index.md#method-cache)

### open() <span id="method-open"></span>

```php
public function open(): mixed
```

Establishes a DB connection.

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

**Returns**

`mixed`

**Throws**

- [`Exception`](/docs/api/yii/db/exception/index.md): if connection fails

### quoteColumnName() <span id="method-quoteColumnName"></span>

```php
public function quoteColumnName(string $name): string
```

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.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | Column name |

**Returns**

`string`: The properly quoted column name

### quoteSql() <span id="method-quoteSql"></span>

```php
public function quoteSql(string $sql): string
```

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`](/docs/api/yii/db/connection/index.md#property-tablePrefix).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$sql` | `string` | The SQL to be quoted |

**Returns**

`string`: The quoted SQL

### quoteTableName() <span id="method-quoteTableName"></span>

```php
public function quoteTableName(string $name): string
```

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.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | Table name |

**Returns**

`string`: The properly quoted table name

### quoteValue() <span id="method-quoteValue"></span>

```php
public function quoteValue(string $value): string
```

Quotes a string value for use in a query.

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

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$value` | `string` | String to be quoted |

**Returns**

`string`: The properly quoted string

**See also**

- <https://www.php.net/manual/en/pdo.quote.php>

### setDriverName() <span id="method-setDriverName"></span>

```php
public function setDriverName(string $driverName): mixed
```

Changes the current driver name.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$driverName` | `string` | Name of the DB driver |

**Returns**

`mixed`

### setQueryBuilder() <span id="method-setQueryBuilder"></span>

```php
public function setQueryBuilder(array $value): mixed
```

Can be used to set [`QueryBuilder`](/docs/api/yii/db/querybuilder/index.md) configuration via Connection configuration array.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$value` | `array` | The [`QueryBuilder`](/docs/api/yii/db/querybuilder/index.md) properties to be configured. |

**Returns**

`mixed`

**Since**

2.0.14

### transaction() <span id="method-transaction"></span>

```php
public function transaction(callable $callback, string|null $isolationLevel = null): mixed
```

Executes callback provided in a transaction.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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 [`Transaction::begin()`](/docs/api/yii/db/transaction/index.md#method-begin) for details. |

**Returns**

`mixed`: Result of callback function

**Throws**

- [`Throwable`](https://www.php.net/manual/en/class.throwable.php): if there is any exception during query. In this case the transaction will be rolled back.

### useMaster() <span id="method-useMaster"></span>

```php
public function useMaster(callable $callback): mixed
```

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();
});
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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. |

**Returns**

`mixed`: The return value of the callback

**Throws**

- [`Throwable`](https://www.php.net/manual/en/class.throwable.php): if there is any exception thrown from the callback

### createPdoInstance() <span id="method-createPdoInstance"></span>

```php
protected function createPdoInstance(): PDO
```

Creates the PDO instance.

This method is called by [`open()`](/docs/api/yii/db/connection/index.md#method-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.

**Returns**

[`PDO`](https://www.php.net/manual/en/class.pdo.php): The pdo instance

### initConnection() <span id="method-initConnection"></span>

```php
protected function initConnection(): mixed
```

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`](/docs/api/yii/db/connection/index.md#property-emulatePrepare) is true, and sets the database [`$charset`](/docs/api/yii/db/connection/index.md#property-charset) if it is not empty. MySQL and MariaDB
connections fall back to `utf8mb4` when neither [`$charset`](/docs/api/yii/db/connection/index.md#property-charset) nor the [`$dsn`](/docs/api/yii/db/connection/index.md#property-dsn) specifies a charset.
For PostgreSQL, an explicitly configured `Schema::$defaultSchema` is applied as the session `search_path`.
It then triggers an [`EVENT_AFTER_OPEN`](/docs/api/yii/db/connection/index.md#event-EVENT_AFTER_OPEN) event.

**Returns**

`mixed`

### openFromPool() <span id="method-openFromPool"></span>

```php
protected function openFromPool(array $pool, array $sharedConfig): yii\db\Connection|null
```

Opens the connection to a server in the pool.

This method implements load balancing and failover among the given list of the servers.
Connections will be tried in random order.
For details about the failover behavior, see [`openFromPoolSequentially()`](/docs/api/yii/db/connection/index.md#method-openFromPoolSequentially).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$pool` | `array` | The list of connection configurations in the server pool |
| `$sharedConfig` | `array` | The configuration common to those given in `$pool`. |

**Returns**

[`Connection`](/docs/api/yii/db/connection/index.md)`|null`: The opened DB connection, or `null` if no server is available

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if a configuration does not specify "dsn"

**See also**

- [`openFromPoolSequentially()`](/docs/api/yii/db/connection/index.md#method-openFromPoolSequentially)

### openFromPoolSequentially() <span id="method-openFromPoolSequentially"></span>

```php
protected function openFromPoolSequentially(array $pool, array $sharedConfig): yii\db\Connection|null
```

Opens the connection to a server in the pool.

This method implements failover among the given list of servers.
Connections will be tried in sequential order. The first successful connection will return.

If [`$serverStatusCache`](/docs/api/yii/db/connection/index.md#property-serverStatusCache) is configured, this method will cache information about
unreachable servers and does not try to connect to these for the time configured in [`$serverRetryInterval`](/docs/api/yii/db/connection/index.md#property-serverRetryInterval).
This helps to keep the application stable when some servers are unavailable. Avoiding
connection attempts to unavailable servers saves time when the connection attempts fail due to timeout.

If none of the servers are available the status cache is ignored and connection attempts are made to all
servers (Since version 2.0.35). This is to avoid downtime when all servers are unavailable for a short time.
After a successful connection attempt the server is marked as available again.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$pool` | `array` | The list of connection configurations in the server pool |
| `$sharedConfig` | `array` | The configuration common to those given in `$pool`. |

**Returns**

[`Connection`](/docs/api/yii/db/connection/index.md)`|null`: The opened DB connection, or `null` if no server is available

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if a configuration does not specify "dsn"

**Since**

2.0.11

**See also**

- [`openFromPool()`](/docs/api/yii/db/connection/index.md#method-openFromPool)
- [`$serverStatusCache`](/docs/api/yii/db/connection/index.md#property-serverStatusCache)