本文实例讲述了Yii框架批量插入数据扩展类的简单实现方法。分享给大家供大家参考,具体如下:
MySQL INSERT语句允许插入多行数据,如下所示:
?
1
|
INSERT INTO tbl_name (a,b,c) VALUES (1,2,3),(4,5,6),(7,8,9);
|
那么要实现批量插入,主要的任务就是按照列顺序,把数据组装成上述格式即可,可以使用sprintf和vsprintf函数来实现。
下面是一个实现批量插入的Yii扩展类的简单示例(支持VARCHAR类型数据):
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
<?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程序设计有所帮助。
相关文章
猜你喜欢
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-06-04 48
-
Mybatis集成Spring的实例代码_动力节点Java 学院整理
2025-05-29 66 -
2025-06-04 105
-
2025-05-29 70
-
使用360免费建站时遇到问题如何解决以确保赚钱计划顺利进行?
2025-06-04 29
热门评论