TDbConnection represents a connection to a database.
TDbConnection works together with {@link TDbCommand}, {@link TDbDataReader}
and {@link TDbTransaction} to provide data access to various DBMS
in a common set of APIs. They are a thin wrapper of the {@link http://www.php.net/manual/en/ref.pdo.php PDO}
PHP extension.
To establish a connection, set {@link setActive Active} to true after
specifying {@link setConnectionString ConnectionString}, {@link setUsername Username}
and {@link setPassword Password}.
Since 3.1.2, the connection charset can be set (for MySQL and PostgreSQL databases only)
using the {@link setCharset Charset} property. The value of this property is database dependant.
e.g. for mysql, you can use 'latin1' for cp1252 West European, 'utf8' for unicode, ...
The following example shows how to create a TDbConnection instance and establish
the actual connection:
$connection=new TDbConnection($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->bindParameter($name1,$value1);
$command->bindParameter($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();
}
TDbConnection provides a set of methods to support setting and querying
of certain DBMS attributes, such as {@link getNullConversion NullConversion}.