yii源码三 -- db

CDbConnection:
path:/framework/db/CDbConnection.php
overview:CDbConnection represents a connection to a database.

工作原理:CDbConnection works together with CDbCommand, CDbDataReader and CDbTransaction to provide data access to various DBMS。且基于PDO扩展。

  首先用$connection = new CDbConnection($dsn,$username,$password)创建一个连接实例,然后调用$connection->active=true启动连接。

用法:
1.创建DB实例并建立连接:

$connection=new CDbConnection($dsn,$username,$password);
$connection->active=true; //建立连接

2.执行sql语句:

$command=$connection->createCommand($sqlStatement);
$command->execute();   //执行非查询语句(insert,delete,update)
$reader=$command->query();//执行查询语句(select)

备注:预处理和绑定参数用法:

$command=$connection->createCommand($sqlStatement);
$command->bindParam($name1,$value1);
$command->bindParam($name2,$value2);
$command->execute();

3.获取结果:

foreach($reader as $row){
      ......  
}

4.事务:

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

5.由于CDbConnection实现了IApplicationComponent接口,所以它可以当作一个application component并且在application配置文件(main.php)里配置数据库连接信息:

array(
     ‘components‘=>array(
         ‘db‘=>array(
              ‘class‘=>‘CDbConnection‘,
              ‘connectionString‘=>‘sqlite:path/to/dbfile‘,
         ),
     ),
)

yii源码三 -- db,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。