這篇文章主要介紹了Yii框架批量插入資料擴展類別的簡單實現方法,涉及Yii擴展類及資料庫相關操作技巧,需要的朋友可以參考下
本文實例講述了Yii框架批量插入資料擴充類別的簡單實作方法。分享給大家供大家參考,具體如下:
MySQL INSERT語句允許插入多行數據,如下所示:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
那麼要實現批次插入,主要的任務就是按照列順序,把資料組裝成上述格式即可,可以使用sprintf和vsprintf函數來實現。
下面是實現批次插入的Yii擴充類別的簡單範例(支援VARCHAR型別資料):
<?php /** * class for sql batch insert */ class CDbBICommand extends CDbCommand{ /** @var CActiveRecord $class */ private $class; /** @var string $insert_tpl */ private $insert_tpl = "insert into %s(%s) "; /** @var string $value_tpl */ private $value_tpl = "(%s)"; /** @var string $query */ public $query; /** @var CDbColumnSchema[] $columns */ private $columns; /** @var boolean $fresh */ private $fresh; /** @param CActiveRecord $class * @param CDbConnection $db */ public function __construct($class,$db){ $this->class = $class; $this->createtpl(); parent::_construct($db); } private function createtpl(){ $this->fresh = true; $value_tpl = ""; $columns_string = ""; $this->columns = $this->class->getMetaData()->tableSchema->columns; $counter = 0; foreach($this->columns as $column){ /** @var CDbColumnSchema $column */ if($column->autoIncrement){ $value_tpl .= "0"; }else{ $value_tpl .= "\"%s\""; } $columns_string .= $column->name; $counter ++; if($counter != sizeof($this->columns)){ $columns_string .= ", "; $value_tpl .= ", "; } } $this->insert_tpl = sprintf($this->insert_tpl, $this->class->tableName(), $columns_string); $this->value_tpl = sprintf($this->value_tpl, $value_tpl); } /** * @param CActiveRecord $record */ public function add($record){ $values = array(); $i = 0; foreach($this->columns as $column){ if($column->autoIncrement){ continue; } $values[$i] = $this->class->{$column->name}; $i ++; } if(!$this->fresh){ $this->query .= ","; }else{ $this->query = "values"; } $this->fresh = false; $this->query .= vsprintf($this->value_tpl, $values); return true; } public function execute(){ $this->setText($this->insert_tpl." ".$this->query); return parent::execute(); } }
使用方法是透過add方法逐一加入數據,然後呼叫execute執行。
以上是Yii中資料的批次插入類別實作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!