MySQL中yii2使用原生sql CURD
$connection = Yii::app()->db; //连接 //查找 $sql = “SELECT * FROM `tbl_user` ORDER BY id DESC”; $command = $connection->createCommand($sql); $result = $command->queryAll();
·
更多yii2使用技巧请参考:http://nai8.me/tool-sc.html
批量插入数据:
Yii::$app->db->createCommand()->batchInsert('user', ['email', 'password', 'first_name'],
[
['james.franklin@example.com', 'changeme7', 'James'],
['linda.marks@example.com', 'changeme7', 'Linda']
['roger.martin@example.com', 'changeme7']
])->execute();
更新数据:
Yii::$app->db->createCommand()->update('user', ['updated_at' => time()], 'id = 2')->execute();
删除数据:
Yii::$app->db->createCommand()->delete('user', 'id = 3')->execute();
获取所有数据(数组返回格式):
Yii::$app->db->createCommand("SELECT * FROM `user`")->queryAll();
查询一条数据:
Yii::$app->db->createCommand("SELECT * FROM `user` WHERE id = 1")->queryOne();
获取一个值:
Yii::$app->db->createCommand("SELECT count(*) AS total FROM `user` WHERE id = 1")->queryScalar();
获取某一列:
Yii::$app->db->createCommand("SELECT username FROM `user`")->queryColumn();
更多推荐
已为社区贡献2条内容
所有评论(0)