// 获得数据库连接
$conn = Yii::$app->db;
// 执行数据库查询语句
Yii::$app->db->createCommand("SELECT * FROM `user`");Yii::$app->db->createCommand("SELECT * FROM `user` WHERE uid=:uid",[":uid"=>1]);Yii::$app->db->createCommand("SELECT * FROM `user` WHERE uid=:uid")->addValue([":uid"=>1]);
// SQL语句插入数据
Yii::$app->db->createCommand('INSERT INTO user (email, password) VALUES("test3@example.com", "test3");')->execute();
// 数组形式插入数据
Yii::$app->db->createCommand()->insert('user', ['email'=>'test4@example.com','password'=>'changeme7','first_name'=>'Test'])->execute();
// 批量插入数据
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();
网友评论