zuixian113 2017-10-21 23:32:36 4027次浏览 0条回复 2 0 0

使用createCommand()函数向数据库添加数据

添加1条数据 Yii::$app->db->createCommand()->insert(表名, ['字段1'=>'字段1内容', '字段2'=>'字段2内容','字段3'=>'字段3内容'])->execute();

public function actionAddOne()
	{
		Yii::$app->db->createCommand()->insert('country',['code'=>'A1','name'=>'A111111','population'=>'123456789'])->execute();   
	}

添加多条数据 Yii::$app->db->createCommand()->batchInsert(表名, ['字段1', '字段2','字段3'], [['字段1内容', '字段2内容','字段3内容'], ['字段1内容', '字段2内容','字段3内容'], ['字段1内容', '字段2内容','字段3内容'], ])->execute();

public function actionAddAll()
	{
		Yii::$app->db->createCommand()->batchInsert('country', ['code', 'name','population'], [    
			['AA', 'Aaaaaa','123456789'],    
			['BB', 'Bbbbbb','123456789'],    
			['CC', 'Cccccc','123456789'],    
		])->execute();  
	}

//[删除]数据

public function actionDeleteOne()
	{
		Yii::$app->db->createCommand()->delete('country',['code'=>'A1'])->execute();   
	}

//[修改]数据

public function actionUpdateOne()
	{
		Yii::$app->db->createCommand()->update('country',['name'=>'A16666','population'=>'233456'],['code'=>'A1'])->execute();   
	}

更多补充

//获取自增ID $id=Yii::$app->db->getLastInsertID();

//[查询]数据 // 查询返回多行:

$command = Yii::$app->db->createCommand('SELECT * FROM post');    
$posts = $command->queryAll();  

// 返回单行

$command = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=1');    
$post = $command->queryOne();  

// 查询多行单值:

$command = Yii::$app->db->createCommand('SELECT title FROM post');    
$titles = $command->queryColumn();  

// 查询标量值/计算值:

$command = Yii::$app->db->createCommand('SELECT COUNT(*) FROM post');    
$postCount = $command->queryScalar();  
    没有找到数据。
您需要登录后才可以回复。登录 | 立即注册