Class CDbConnection
CDbConnection represents a connection to a database.
CDbConnection works together with CDbCommand
, CDbDataReader
and CDbTransaction
to provide data access to various DBMS in a common
set of APIs. They are a thin wrapper of the PDO PHP extension.
To establish a connection, set setActive active to true after
specifying CDbConnection::$connectionString
, CDbConnection::$username
and CDbConnection::$password
.
The following example shows how to create a CDbConnection instance and establish the actual connection:
$connection=new CDbConnection($dsn,$username,$password); $connection->active=true;
After the DB connection is established, one can execute an SQL statement like the following:
$command=$connection->createCommand($sqlStatement); $command->execute(); // a non-query SQL statement execution // or execute an SQL query and fetch the result set $reader=$command->query(); // each $row is an array representing a row of data foreach($reader as $row) ...
One can do prepared SQL execution and bind parameters to the prepared SQL:
$command=$connection->createCommand($sqlStatement); $command->bindParam($name1,$value1); $command->bindParam($name2,$value2); $command->execute();
To use transaction, do like the following:
$transaction=$connection->beginTransaction(); try { $connection->createCommand($sql1)->execute(); $connection->createCommand($sql2)->execute(); //.... other SQL executions $transaction->commit(); } catch(Exception $e) { $transaction->rollback(); }
CDbConnection also provides a set of methods to support setting and querying of certain DBMS attributes, such as getNullConversion nullConversion.
Since CDbConnection implements the interface IApplicationComponent, it can be used as an application component and be configured in application configuration, like the following,
array( 'components'=>array( 'db'=>array( 'class'=>'CDbConnection', 'connectionString'=>'sqlite:path/to/dbfile', ), ), )
Use the driverName property if you want to force the DB connection to
use a particular driver by the given name, disregarding of what was set in the
CDbConnection::$connectionString
property. This might be useful when working with ODBC
connections. Sample code:
'db'=>array( 'class'=>'CDbConnection', 'driverName'=>'mysql', 'connectionString'=>'odbc:Driver={MySQL};Server=127.0.0.1;Database=test', 'username'=>'', 'password'=>'', ),
- CComponent
- CApplicationComponent implements IApplicationComponent
- CDbConnection
Copyright: 2008-2013 Yii Software LLC
License: http://www.yiiframework.com/license/
Author: Qiang Xue <qiang.xue@gmail.com>
Since: 1.0
Located at x2engine/framework/db/CDbConnection.php
public
|
#
__construct( string $dsn = '', string $username = '', string $password = '' )
Constructor. Note, the DB connection is not established when this connection instance is created. Set setActive active property to true to establish the connection. |
public
array
|
|
public static
array
|
|
public
|
#
init( )
Initializes the component. This method is required by |
public
boolean
|
|
public
|
|
public
static
|
#
cache( integer $duration,
Sets the parameters about query caching. This method can be used to enable or disable query caching. By setting the $duration parameter to be 0, the query caching will be disabled. Otherwise, query results of the new SQL statements executed next will be saved in cache and remain valid for the specified duration. If the same query is executed again, the result may be fetched from cache directly without actually executing the SQL statement. |
protected
|
|
protected
|
|
protected
|
#
createPdoInstance( )
Creates the PDO instance. When some functionalities are missing in the pdo driver, we may use an adapter class to provide them. |
protected
|
#
initConnection(
Initializes the open db connection. This method is invoked right after the db connection is established. The default implementation is to set the charset for MySQL, MariaDB and PostgreSQL database connections. |
public
|
|
public
|
|
public
|
|
public
|
|
public
|
|
public
|
|
public
string
|
#
getLastInsertID( string $sequenceName = '' )
Returns the ID of the last inserted row or sequence value. |
public
string
|
|
public
string
|
#
quoteTableName( string $name )
Quotes a table name for use in a query. If the table name contains schema prefix, the prefix will also be properly quoted. |
public
string
|
#
quoteColumnName( string $name )
Quotes a column name for use in a query. If the column name contains prefix, the prefix will also be properly quoted. |
public
integer
|
|
public
mixed
|
|
public
|
|
public
mixed
|
|
public
|
|
public
boolean
|
#
getAutoCommit( )
Returns whether creating or updating a DB record will be automatically committed. Some DBMS (such as sqlite) may not support this feature. |
public
|
#
setAutoCommit( boolean $value )
Sets whether creating or updating a DB record will be automatically committed. Some DBMS (such as sqlite) may not support this feature. |
public
boolean
|
#
getPersistent( )
Returns whether the connection is persistent or not. Some DBMS (such as sqlite) may not support this feature. |
public
|
#
setPersistent( boolean $value )
Sets whether the connection is persistent or not. Some DBMS (such as sqlite) may not support this feature. |
public
string
|
|
public
|
#
setDriverName( string $driverName )
Changes the name of the DB driver. Overrides value extracted from the |
public
string
|
|
public
string
|
#
getConnectionStatus( )
Returns the status of the connection. Some DBMS (such as sqlite) may not support this feature. |
public
boolean
|
|
public
string
|
|
public
string
|
|
public
integer
|
|
public
mixed
|
|
public
|
|
public
array
|
|
public
|
|
public
array
|
#
getStats( )
Returns the statistical results of SQL executions. The results returned
include the number of SQL statements executed and the total time spent. In order
to use this method, |
getIsInitialized()
|
public
string
|
$connectionString |
|
#
The Data Source Name, or DSN, contains the information required to connect to the database. |
public
string
|
$username | '' |
#
the username for establishing DB connection. Defaults to empty string. |
public
string
|
$password | '' |
#
the password for establishing DB connection. Defaults to empty string. |
public
integer
|
$schemaCachingDuration | 0 |
#
number of seconds that table metadata can remain valid in cache. Use 0 or negative value to indicate not caching schema. If greater than 0 and the primary cache is enabled, the table metadata will be cached. |
public
array
|
$schemaCachingExclude | array() |
#
list of tables whose metadata should NOT be cached. Defaults to empty array. |
public
string
|
$schemaCacheID | 'cache' |
#
the ID of the cache application component that is used to cache the table metadata. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable caching table metadata. |
public
integer
|
$queryCachingDuration | 0 |
#
number of seconds that query results can remain valid in cache. Use 0 or negative value to indicate not caching query results (the default behavior). In order to enable query caching, this property must be a positive integer
and The method |
public
|
$queryCachingDependency |
|
#
the dependency that will be used when saving query results into cache. |
public
integer
|
$queryCachingCount | 0 |
#
the number of SQL statements that need to be cached next. If this is 0, then even if query caching is enabled, no query will be cached. Note that each time after executing a SQL statement (whether executed on DB server or fetched from query cache), this property will be reduced by 1 until 0. |
public
string
|
$queryCacheID | 'cache' |
#
the ID of the cache application component that is used for query caching. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable query caching. |
public
boolean
|
$autoConnect | true |
#
whether the database connection should be automatically established the component is being initialized. Defaults to true. Note, this property is only effective when the CDbConnection object is used as an application component. |
public
string
|
$charset |
|
#
the charset used for database connection. The property is only used for MySQL, MariaDB and PostgreSQL databases. Defaults to null, meaning using default charset as specified by the database. Note that if you're using GBK or BIG5 then it's highly recommended to update to PHP 5.3.6+ and to specify charset via DSN like 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'. |
public
boolean
|
$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. Note, this property is only effective for PHP 5.1.3 or above. The default value is null, which will not change the ATTR_EMULATE_PREPARES value of PDO. |
public
boolean
|
$enableParamLogging | false |
#
whether to log the values that are bound to a prepare SQL statement. Defaults to false. During development, you may consider setting this property to true so that parameter values bound to SQL statements are logged for debugging purpose. You should be aware that logging parameter values could be expensive and have significant impact on the performance of your application. |
public
boolean
|
$enableProfiling | false |
#
whether to enable profiling the SQL statements being executed. Defaults to false. This should be mainly enabled and used during development to find out the bottleneck of SQL executions. |
public
string
|
$tablePrefix |
|
#
the default prefix for table names. Defaults to null, meaning no table prefix. By setting this property, any token like '{{tableName}}' in CDbCommand::text will be replaced by 'prefixTableName', where 'prefix' refers to this property value. |
public
array
|
$initSQLs |
|
#
list of SQL statements that should be executed right after the DB connection is established. |
public
array
|
$driverMap | array(
'cubrid'=>'CCubridSchema', // CUBRID
'pgsql'=>'CPgsqlSchema', // PostgreSQL
'mysqli'=>'CMysqlSchema', // MySQL
'mysql'=>'CMysqlSchema', // MySQL,MariaDB
'sqlite'=>'CSqliteSchema', // sqlite 3
'sqlite2'=>'CSqliteSchema', // sqlite 2
'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
'sqlsrv'=>'CMssqlSchema', // Mssql
'oci'=>'COciSchema', // Oracle driver
) |
#
mapping between PDO driver and schema class name. A schema class can be specified using path alias. |
public
string
|
$pdoClass | 'PDO' |
#
Custom PDO wrapper class. |
$behaviors
|
public
boolean
|
$active |
#
Whether the DB connection is established. |
public
|
$pdoInstance |
#
The PDO instance, null if the connection is not established yet. |
public
|
$currentTransaction |
#
The currently active transaction. Null if no active transaction. |
public
|
$schema |
#
The database schema for the current connection. |
public
|
$commandBuilder |
#
The command builder. |
public
string
|
$lastInsertID |
#
The row ID of the last row inserted, or the last value retrieved from the sequence object. |
public
mixed
|
$columnCase |
#
The case of the column names. |
public
mixed
|
$nullConversion |
#
How the null and empty strings are converted. |
public
boolean
|
$autoCommit |
#
Whether creating or updating a DB record will be automatically committed. |
public
boolean
|
$persistent |
#
Whether the connection is persistent or not. |
public
string
|
$driverName |
#
Name of the DB driver. This property is read-write since 1.1.16. Before 1.1.15 it was read-only. |
public
string
|
$clientVersion |
#
The version information of the DB driver. |
public
string
|
$connectionStatus |
#
The status of the connection. |
public
boolean
|
$prefetch |
#
Whether the connection performs data prefetching. |
public
string
|
$serverInfo |
#
The information of DBMS server. |
public
string
|
$serverVersion |
#
The version information of DBMS server. |
public
integer
|
$timeout |
#
Timeout settings for the connection. |
public
array
|
$attributes |
#
Attributes (name=>value) that are previously explicitly set for the DB connection. |
public
array
|
$stats |
#
The first element indicates the number of SQL statements executed, and the second element the total time spent in SQL execution. |
$isInitialized
|