Yii使用DAO操作数据库

110 阅读1分钟
DAO获取一条记录:

1
2
3
4
5
6
$sql="select title, id from {{blog}} where id = :id";
$command= Yii::app()->db->createCommand($sql);
$id= (int)$_GET['id'];
$command->bindParam(":id",$id,PDO::PARAM_INT);
$data=$command->queryRow();
//方法 bindParam() 和 bindValue() 非常相似。唯一的区别就是前者使用一个 PHP 变量绑定参数, 而后者使用一个值。对于那些内存中的大数据块参数,处于性能的考虑,应优先使用前者。

获取多条记录:

1
2
3
$sql="select title, id from {{blog}}";
$command= Yii::app()->db->createCommand($sql);
$data=$command->queryAll();

获取一条记录的某个字段:

1
2
3
4
5
$sql="select title from {{blog}} where id = :id";
$command= Yii::app()->db->createCommand($sql);
$id= (int)$_GET['id'];
$command->bindParam(":id",$id,PDO::PARAM_INT);
$title=$command->queryScalar();

使用事务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$transaction=Yii::app()->db->beginTransaction();

try

{
$sql="update {{blog}} set title = 'abc' where id = 2";

Yii::app()->db->createCommand($sql)->execute();


$transaction->commit();

}

catch(Exception$e)

{

$transaction->rollback();

}

插入数据:

1
2
3
4
5
6
7
8
9
$sql="insert into {{blog}}(title) values(:title)";
$command= Yii::app()->db->createCommand($sql);
$title='abc';
$command->bindParam(":title",$title, PDO::PARAM_STR);
$command->execute();

$title='bbbbb';
$command->bindParam(":title",$title, PDO::PARAM_STR);
$command->execute();