码迷,mamicode.com
首页 > 数据库 > 详细

yii源码三 -- db

时间:2014-07-18 18:38:26      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   strong   文件   数据   

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,布布扣,bubuko.com

yii源码三 -- db

标签:style   blog   color   strong   文件   数据   

原文地址:http://www.cnblogs.com/thinksasa/p/3853341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!