yii2数据库访问对象

yii2数据库访问对象

配置数据库链接

$db = new yii\db\Connection([
            'dsn' => 'mysql:host=localhost;dbname=xhj',
            'username' => 'root',
            'password' => '123456',
            'charset' => 'utf8',
        ]);

或 配置文件 config/web.php 添加

 'components' => [
        // ...
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=example',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],
    ],

查询

        //$user = Yii::$app->db->createCommand('SELECT * FROM country')->queryAll();
        
        $result = $db->createCommand('SELECT * FROM xhj_backend_member')->queryAll();
        $result = $db->createCommand('SELECT * FROM xhj_backend_member where id= 8')->queryOne();
        $result = $db->createCommand('SELECT username FROM xhj_backend_member')->queryColumn();
        $result = $db->createCommand('SELECT COUNT(*) FROM xhj_backend_member')->queryScalar();

        $id = 8;
        $result = $db->createCommand('SELECT * FROM xhj_backend_member where id=:id')->bindValue(':id',$id)->queryOne();

        $params = [':id' => 1, ':status' => 1];
        $result = $db->createCommand('SELECT * FROM xhj_backend_member where id=:id AND status=:status')->bindValues($params)->queryOne();
        $result = $db->createCommand('SELECT * FROM xhj_backend_member where id=:id AND status=:status',$params)->queryOne();

CURD

        // Yii::$app->db->createCommand('UPDATE country SET population=112233 WHERE `code`="US"')->execute();

       // Yii::$app->db->createCommand()->insert('country', ['code' => 'AD', 'name' => '艾莉','population'=>2])->execute();
       // Yii::$app->db->createCommand()->update('country', ['population' => 222], ['code'=>'AD'])->execute();

        //Yii::$app->db->createCommand()->delete('country', ['code'=>'AD'])->execute();

        Yii::$app->db->createCommand()->batchInsert('country', ['code','name','population'],[['code1', 'name1', 1], ['code2', 'name2', 2],['code3', 'name3', 3]])->execute();

事务

        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $db->createCommand($sql1)->execute();
            $db->createCommand($sql2)->execute();
            // ... executing other SQL statements ...

            $transaction->commit();
        } catch(\Exception $e) {
            $transaction->rollBack();
            throw $e;
        } catch(\Throwable $e) {
            $transaction->rollBack();
            throw $e;
        }
posted @   胡勇健  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示