第一种方法: 使用insert into 插入 for 循环sql插入数据
$param = [‘id’=>1];
set_time_limit(0);
echo date(“H:i:s”);
for($i=0;$i<2000000;$i++){
$db->Insert($param,$table,true);
};
echo date(“H:i:s”);
第二种方法: 使用事务提交,批量插入数据库(每隔10W条提交下)最后显示消耗的时间为:22:56:13 23:04:00 ,一共8分13秒 ,代码如下:
echo date(“H:i:s”);
$connect_mysql->query(‘BEGIN');
$params = array(‘value'=>'50′);
for($i=0;$i<2000000;$i++){
$connect_mysql->insert($params);
if($i%100000==0){
$connect_mysql->query(‘COMMIT');
$connect_mysql->query(‘BEGIN');
}
}
$connect_mysql->query(‘COMMIT');
echo date(“H:i:s”);
第三种方法:使用优化SQL语句:将SQL语句进行拼接,使用insert into table()values(),(),(),()然后再一次性插入,如果字符串太长,则需要配置下MYSQL,在mysql命令下运行:set global max_allowed_packet = 2*1024*1024*10
$structinfo =[]; //查询的数组
$data =[]; //需要插入的数据组合成数组
foreach ($structInfo as $k => $v){
$data[$k]['company_k'] = $v['company_k'];
$data[$k]['company_name'] = $v['company_name'];
$data[$k]['dept_k'] = $v['dept_k'];
$data[$k]['dept_name'] = $v['dept_name'];
$data[$k]['one_lead_code'] = $v['one_lead_code'];
$data[$k]['one_lead_realname'] = $v['one_lead_realname'];
$data[$k]['two_lead_code'] = $v['two_lead_code'];
$data[$k]['two_lead_realname'] = trim($v['two_lead_realname']);
$data[$k]['company_admin_code'] = $v['company_admin_code'];
$data[$k]['company_admin_realname']= $v['company_admin_realname'];
$data[$k]['user_code'] = $v['user_code'];
$data[$k]['realname'] = $v['realname'];
$data[$k]['job_name'] = $v['job_name'];
$data[$k]['user_level']= $v['level'];
$data[$k]['in_date'] = $v['in_date'];
}
var_dump(array_keys($data[0]));
$fildString = "". implode(',',array_keys($data[0])).""; //要插入的表里的字段
$sql = "INSERT INTO `lzh_score_template`($fildString)VALUE ";
$string = "'" .join("','",$data[0])."'";
//join函数是implode函数的别名 把数组元素分割为字符串implode(separator,array)separator规定数组元素之间放置的内容
foreach ($dataas $k => $v){
$sql .= "('" .join("','",$v)."'),"; //以','分割字符串,然后在在两边拼接分号'',这样元素值就以分号分割了
}
$sql = substr($sql,0,strlen($sql)-1);