yii使用原生态sql语句操作数据库范例代码

  • 时间:
  • 浏览:18

yii框架使用原生态的sql语句也是可以对数据库进行操作的,以下就是详细的操作代码,很详细:


PHP

class IndexController extends Controller

{

public function actionIndex()

{

$con = Yii::app()->db;//数据库连接

//查询

$sql = "select * from user";

$command = $con->createCommand($sql);

$res = $command->queryAll();

print_r($res);

//插入

$sql = "insert into user (integral,name) values (999,'www.codeinlife.com')";

$command = $con->createCommand($sql);

$res = $command->execute();

print_r($res);

//删除

$sql = "delete from user where id=1";

$command = $con->createCommand($sql);

$res = $command->execute();

print_r($res);

//查询结果

$sql = "select * from user";

$command = $con->createCommand($sql);

$res = $command->queryAll();

print_r($res);


}


}


运行后的结果为:


Array

(

    [0] => Array

        (

            [id] => 1

            [integral] => 3000

            [name] => aa

        )


    [1] => Array

        (

            [id] => 2

            [integral] => 2000

            [name] => aa

        )


    [2] => Array

        (

            [id] => 3

            [integral] => 1000

            [name] => bb

        )


)


1


1


Array

(

    [0] => Array

        (

            [id] => 2

            [integral] => 2000

            [name] => aa

        )


    [1] => Array

        (

            [id] => 3

            [integral] => 1000

            [name] => bb

        )


    [2] => Array

        (

            [id] => 4

            [integral] => 999

            [name] => www.codeinlife.com

        )


)


这种方法,有些时候还是能够用得到的。