您的位置:首页 > 编程语言 > PHP开发

YII自学笔记(二)

2016-05-24 14:48 363 查看
数据库

1.数据库访问对象(DAO)

Yii DAO基于PDO创建的

Yii DAO 主要包含如下四个类:

CDbConnection: 代表一个数据库连接。

CDbCommand: 代表一条通过数据库执行的 SQL 语句。

CDbDataReader: 代表一个只向前移动的,来自一个查询结果集中的行的流。

CDbTransaction: 代表一个数据库事务。

数据库链接方式
第一种:直接创建CDbConnection对象
$connection=new CDbConnection($dsn,$username,$password);
// 建立连接。你可以使用  try...catch 捕获可能抛出的异常
$connection->active=true;
......
$connection->active=false;  // 关闭连接

目前DSN常用格式如下:
SQLite: sqlite:/path/to/dbfile
MySQL: mysql:host=localhost;dbname=testdb
PostgreSQL: pgsql:host=localhost;port=5432;dbname=testdb
SQL Server: mssql:host=localhost;dbname=testdb
Oracle: oci:dbname=//localhost:1521/testdb

第二种:在应用配置中配置 main.php
array(
......
'components'=>array(
......
'db'=>array(
'class'=>'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=testdb',
'username'=>'root',
'password'=>'password',
'emulatePrepare'=>true,  // needed by some MySQL installations
),
),
)

这样就可以通过 Yii::app()->db 访问数据库连接了。

2.执行SQL
$connection=Yii::app()->db;   // 假设你已经建立了一个 "db" 连接
$command=$connection->createCommand($sql); //创建CDbCommand 实例
一条 SQL 语句会通过 CDbCommand 以如下两种方式被执行
execute(): 执行一个无查询 (non-query)SQL语句, 例如 INSERT, UPDATE 和 DELETE 。如果成功,它将返回此执行所影响的行数。
query(): 执行一条会返回若干行数据的 SQL 语句,例如 SELECT。 如果成功,它将返回一个CDbDataReader 实例,通过此实例可以遍历数据的结果行。
如果发生错误将抛出异常
$rowCount=$command->execute();   // 执行无查询 SQL
$dataReader=$command->query();   // 执行一个 SQL 查询,返回数据对象
$rows=$command->queryAll();      // 查询并返回结果中的所有行,返回行结果
$row=$command->queryRow();       // 查询并返回结果中的第一行
$column=$command->queryColumn(); // 查询并返回结果中的第一列
$value=$command->queryScalar();  // 查询并返回结果中第一行的第一个字段

3.获取查询结果
可以通过两种方式获取$command->query()结果
$dataReader=$command->query();
第一:
// 重复调用 read() 直到它返回 false
while(($row=$dataReader->read())!==false) { ... }
第二:
foreach($dataReader as $row) { ... }

也可以一下子获取全部数据
$rows=$dataReader->readAll();

4.使用事物处理
$transaction=$connection->beginTransaction();
try
{
$connection->createCommand($sql1)->execute();
$connection->createCommand($sql2)->execute();
//.... other SQL executions
$transaction->commit();
}
catch(Exception $e) // 如果有一条查询失败,则会抛出异常
{
$transaction->rollBack();
}

5.  绑定参数
可避免大部分SQL注入,提高SQL执行效率
可以通过CDbCommand::bindParam()或者 CDbCommand::bindValue() 实现参数替换
使用CDbCommand::bindParam()如下:
// 一条带有两个占位符 ":username" 和 ":email"的 SQL
$sql="INSERT INTO tbl_user (username, email) VALUES(:username,:email)";
$command=$connection->createCommand($sql);
// 用实际的用户名替换占位符 ":username"
$command->bindParam(":username",$username,PDO::PARAM_STR);
// 用实际的 Email 替换占位符 ":email"
$command->bindParam(":email",$email,PDO::PARAM_STR);
$command->execute();
// 使用新的参数集插入另一行
$command->bindParam(":username",$username2,PDO::PARAM_STR);
$command->bindParam(":email",$email2,PDO::PARAM_STR);
$command->execute();


QueryBuilder

Yii查询构建器提供了一种面向对象的方式编写SQL语句.它允许开发者使用类的方法和属性来指定各个部分的SQL语句。如下:

user=Yii::app()−>db−>createCommand()−>select(‘id,username,profile′)−>from(‘tbluseru′)−>join(‘tblprofilep′,‘u.id=p.userid′)−>where(‘id=:id′,array(‘:id′=>id))

->queryRow();

1.生成查询构建器
$command = Yii::app()->db->createCommand();

2.构建数据检索查询
select(): specifies the SELECT part of the query  //指定查询部分
selectDistinct(): specifies the SELECT part of the query and turns on the DISTINCT flag //指定查询部分并且去重
from(): specifies the FROM part of the query  //指定FROM
where(): specifies the WHERE part of the query //指定条件
andWhere(): appends condition to the WHERE part of the query with AND operator  //增加与条件
orWhere(): appends condition to the WHERE part of the query with OR operator   //增加或条件
join(): appends an inner join query fragment   //指定内连接部分
leftJoin(): appends a left outer join query fragment  //指定左连接部分
rightJoin(): appends a right outer join query fragment  //指定右连接部分
group(): specifies the GROUP BY part of the query   //指定分组部分
having(): specifies the HAVING part of the query    //指定分组查询条件部分
order(): specifies the ORDER BY part of the query  //指定排序
limit(): specifies the LIMIT part of the query    //指定记录范围
offset(): specifies the OFFSET part of the query  //指定偏移量部分
union(): appends a UNION query fragment    //指定联合结果部分


Active Record

AR是ORM技术,通过更加面向对象操作数据库。

如:Post是表对应的对象

post=newPost;post->title=’sample post’;

post−>content=′postbodycontent′;post->save();

这样就完成了新增记录。

1.定义AR,继承CActiveRecord
class Post extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}

public function tableName()
{
return 'tbl_post';
}
}

AR被引入方式,在main.php
return array(
'import'=>array(
'application.models.Post',
),
);

获取表面可以通过没有前缀的表名
public function tableName()
{
return '{{post}}';
}

访问一个表中不存在的列名,会抛异常

AR依靠表中良好定义的主键,如果没有则必须指定主键,可以通过一下方法指定主键
public function primaryKey()
{
return 'id';
// 对于复合主键,要返回一个类似如下的数组
// return array('pk1', 'pk2');
}
2.读取记录
// 查找满足指定条件的结果中的第一行
$post=Post::model()->find($condition,$params);
// 查找具有指定主键值的那一行
$post=Post::model()->findByPk($postID,$condition,$params);
// 查找具有指定属性值的行
$post=Post::model()->findByAttributes($attributes,$condition,$params);
// 通过指定的 SQL 语句查找结果中的第一行
$post=Post::model()->findBySql($sql,$params);
// 获取满足指定条件的行数
$n=Post::model()->count($condition,$params);
// 通过指定的 SQL 获取结果行数
$n=Post::model()->countBySql($sql,$params);
// 检查是否至少有一行复合指定的条件
$exists=Post::model()->exists($condition,$params);

调用 find 时,我们使用 $condition 和 $params 指定查询条件。此处 $condition 可以是 SQL 语句中的 WHERE 字符串,$params 则是一个参数数组,其中的值应绑定到 $condation 中的占位符。例如:
// 查找 postID=10 的那一行
$post=Post::model()->find('postID=:postID', array(':postID'=>10));

3.更新记录
在 AR 实例填充了列的值之后,我们可以改变它们并把它们存回数据表。
$post=Post::model()->findByPk(10);
$post->title='new post title';
$post->save(); // 将更改保存到数据库
这个需要载入再修改
直接更新数据表中的一行或多行而不首先载入也是可行的。 AR 提供了如下方便的类级别方法实现此目的
// 更新符合指定条件的行
Post::model()->updateAll($attributes,$condition,$params);
// 更新符合指定条件和主键的行
Post::model()->updateByPk($pk,$attributes,$condition,$params);
// 更新满足指定条件的行的计数列
Post::model()->updateCounters($counters,$condition,$params);
在上面的代码中, $attributes 是一个含有以 列名作索引的列值的数组; $counters 是一个由列名索引的可增加的值的数组;$condition 和 $params 在前面的段落中已有描述。

4.删除记录
$post=Post::model()->findByPk(10); // 假设有一个帖子,其 ID 为 10
$post->delete(); // 从数据表中删除此行

也可以不需要先载入再删除
// 删除符合指定条件的行
Post::model()->deleteAll($condition,$params);
// 删除符合指定条件和主键的行
Post::model()->deleteByPk($pk,$condition,$params);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  yii pdo