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‘, ), ), )
时间: 2024-10-25 07:20:06