zoukankan      html  css  js  c++  java
  • php批量同步数据

    php批量同步流程

    1. 首先分页获取数据
    2. 创建临时表
    3. 批量添加数据
    4. 备份原表
    5. 删除原表
    6. 修改临时表表名改为原表

    代码

      1 <?php
      2 
      3 class Stock{
      4 
      5     private $database = "stockdb";
      6     private $table = "s_stock";
      7     private $tmp_table = "s_stock_tmp";
      8     private $url;
      9     private $link;
     10     private $queryStr;
     11     private $lastInsId;
     12     private $num_rows;
     13 
     14     public function __construct(){
     15 
     16     }
     17 
     18     public function mysql_connect($dbConfig=array()){
     19         $this->link = new mysqli($dbConfig['host'],$dbConfig['user'],$dbConfig['pass'],$dbConfig['database'],$dbConfig['port']);
     20         if($this->link->connect_errno)
     21         {
     22             echo $this->link->connect_errno.' '.$this->link->connect_error;
     23         }
     24         $dbVersion = $this->link->server_version;
     25         if ($dbVersion >= "4.1") {
     26             // 设置数据库编码 需要mysql 4.1.0以上支持
     27             $this->link->query("SET NAMES '".$dbConfig['charset']."'");
     28         }
     29         //设置 sql_model
     30         if($dbVersion >'5.0.1'){
     31             $this->link->query("SET sql_mode=''");
     32         }
     33     
     34     }
     35 
     36     /**
     37      * 判断数据表是否存在
     38      * @param $table
     39      * @return bool
     40      */
     41     public function isDBExist($database,$table){
     42         $n = mysqli_query($this->link,"select * from information_schema.tables where TABLE_SCHEMA='". $database ."' and TABLE_NAME = '". $table."'");
     43         if($n->num_rows==1){
     44             return true;//存在
     45         }else{
     46             return false;//不存在
     47         }
     48     }
     49 
     50 
     51     /**
     52      * 执行sql
     53      * @param $table
     54      * @return bool
     55      */
     56     public function execute($str) {
     57         
     58         if ( !$this->link ) return false;
     59         $this->queryStr = $str;
     60         $result =   $this->link->query($str);
     61 
     62         if ( false === $result ) {
     63             return false;
     64         } else {
     65             $this->numRows = $this->link->affected_rows;
     66             $this->lastInsId = $this->link->insert_id;
     67             return array('numRows'=>$this->numRows, 'lastInsId'=>$this->lastInsId);
     68         }
     69     }
     70 
     71 
     72     /**
     73      * 获取13位时间戳
     74      * @return float
     75      */
     76     function getMillisecond(){
     77         list($t1, $t2) = explode(' ', microtime());
     78         return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
     79     }
     80 
     81 
     82     /**
     83      * 定义添加数据的方法
     84      * @param string $table 表名
     85      * @param string orarray $data [数据]
     86      * @return int 最新添加的id
     87      */
     88     function insertOne($table,$data){
     89         if(empty($table) || empty($data)){
     90             return false;
     91         }
     92         //遍历数组,得到每一个字段和字段的值
     93         $key_str='';
     94         $v_str='';
     95         foreach($data as $key=>$v){
     96             if(empty($v) && $v !== 0){
     97                 continue;
     98             }
     99             //$key的值是每一个字段s一个字段所对应的值
    100             $key_str.=$key.',';
    101             $v_str.="'$v',";
    102         }
    103         $key_str=trim($key_str,',');
    104         $v_str=trim($v_str,',');
    105         //判断数据是否为空
    106         $sql="insert into $table ($key_str) values ($v_str)";
    107         $result = $this->execute($sql);
    108         //返回上一次增加操做产生ID值
    109         if ( false === $result ) {
    110             return false;
    111         } else {
    112             return $result;
    113         }
    114     }
    115 
    116     /**
    117      * 定义添加多条数据的方法
    118      * @param string $table 表名
    119      * @param string orarray $data [数据]
    120      * @return int 最新添加的id
    121      */
    122     function insertAll($table,$dataArr){
    123         if(empty($table) || empty($dataArr)){
    124             return false;
    125         }
    126 
    127         $val_str = '';
    128         foreach($dataArr as $v){
    129             $one_val = '(';
    130             foreach($v as $kk => $vv){
    131                 $one_val .= "'{$vv}',";
    132             }
    133             $one_val = rtrim($one_val,',');
    134             $one_val .= '),';
    135             $val_str .= $one_val;
    136         }
    137         $val_str = rtrim($val_str,',');
    138         $key = implode(",",array_keys($dataArr[0])); //获取key
    139         $sql = "INSERT INTO ".$table." (".$key.")VALUE ".$val_str;
    140         $result = $this->execute($sql);
    141         //返回上一次增加操做产生ID值
    142         if ( false === $result ) {
    143         } else {
    144             return $result;
    145         }
    146     }
    147 
    148 
    149 
    150 
    151     /**
    152      * 创建临时表
    153      * @return mixed
    154      */
    155     function createTmpStock(){
    156         $isTableName = $this->isDBExist($this->database,$this->tmp_table);
    157         if($isTableName){
    158             return true;
    159         }else{
    160             $sql = "CREATE TABLE ".$this->database.".`".$this->tmp_table."` (
    161     `Id` int(11) NOT NULL AUTO_INCREMENT,
    162     `companyId` int(11) DEFAULT NULL COMMENT '公司ID',
    163     `webId` int(11) DEFAULT NULL,
    164     `pid` int(11) DEFAULT NULL COMMENT '产品id',
    165     `productCode` varchar(50) DEFAULT NULL COMMENT '产品编码',
    166     `OEcode` varchar(50) DEFAULT NULL,
    167     `OEcode1` varchar(50) DEFAULT NULL,
    168     `productName` varchar(20) DEFAULT NULL COMMENT '产品名称',
    169     `eName` varchar(255) DEFAULT NULL COMMENT '产品英文名',
    170     `unit` varchar(10) DEFAULT NULL COMMENT '单位',
    171     `specification` varchar(255) DEFAULT NULL COMMENT '规格',
    172     `place` varchar(255) DEFAULT NULL COMMENT '产地',
    173     `brand` varchar(50) DEFAULT NULL COMMENT '零件品牌',
    174     `ppcode` varchar(255) DEFAULT NULL COMMENT '零件品牌厂家编码',
    175     `model` varchar(255) DEFAULT NULL COMMENT '车型',
    176     `modelAll` varchar(255) DEFAULT NULL COMMENT '所有适配车型',
    177     `quality` varchar(20) DEFAULT NULL COMMENT '品质',
    178     `num` int(11) DEFAULT NULL COMMENT '库存数量',
    179     `retailPrice` double DEFAULT NULL COMMENT '零售价',
    180     `ctime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
    181     `utime` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
    182     PRIMARY KEY (`Id`),
    183     UNIQUE KEY `CWP` (`webId`,`pid`) USING BTREE COMMENT '公司ID+网站所属ID+产品ID'
    184     ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='库存表';";
    185 
    186             $ret =$this->execute($sql);
    187             return $ret;
    188 
    189         }
    190     }
    191 
    192 
    193     /**
    194      * 修改表名
    195      * @return mixed
    196      */
    197     function saveTableName(){
    198         $time = date("YmdHis");
    199         $newTableName = $this->table."_".$time;
    200         $sql = "ALTER TABLE ".$this->database.".`".$this->table."` RENAME TO ".$this->database.".`".$newTableName."`";
    201         $newSql = "ALTER TABLE ".$this->database.".`".$this->tmp_table."` RENAME TO ".$this->database.".`".$this->table."`";
    202         $this->execute($sql);
    203         return $this->execute($newSql);
    204 
    205     }
    206 
    207 
    208 
    209 
    210     /**
    211      * 增量式批量同步数据
    212      */
    213     function pushStockAction(){
    214         header('Content-type:text/html;charset=utf-8');
    215         set_time_limit(0); //取消脚本执行延时上限
    216         ignore_user_abort(TRUE); //如果客户端断开连接,不会引起脚本abort
    217         $beginTime = getMillisecond();
    218         echo "开始时间:{$beginTime}
    ";
    219         $yxM = new YxstockapiModel();
    220         $retArr = $yxM->requestYXApiAllkckeyStock();//生成key
    221         $allkckey = $retArr["allkckey"]; # 获取所有库存的秘钥,有效期2小时
    222         $pcount = $retArr["pcount"]; # 库存总批数,通过pcount知道获取所有库存需要分多少批获取,从1至N
    223         $dcount = $retArr["dcount"]; # 所有库存总条数
    224 
    225 
    226         //根据批次获取数据
    227         $num = 0;
    228         for($i=1; $i< $pcount+1; $i++){
    229             //开始同步的时候创建临时表,用以同步数据
    230             if($i == 1){
    231                 $yxM->createTmpStock();
    232             }
    233             $ret = $yxM->requestYXApiAllStock($allkckey,$i);//批量同步数据
    234             $num += $ret["numRows"];
    235     //            sleep(5);//睡眠5秒防止内存溢出
    236 
    237         }
    238         if($num > 0){
    239             //所有的循环结束之后在修改表名
    240             $yxM->saveTableName();
    241         }
    242         
    243         // 计算总耗时和同步数据条数
    244         $endTime = getMillisecond();
    245         $timeConsuming = $endTime - $beginTime;
    246         echo "
    
    同步时间总耗时:{$timeConsuming}
    库存总条数:{$dcount}
    同步库存总条数:{$num}";
    247 
    248 
    249     }
    250 
    251 
    252 
    253 }
    简单的同步
  • 相关阅读:
    JAVA与.NET的相互调用——通过Web服务实现相互调用
    WCF大数据量传输配置
    WCF大数据量传输解决方案
    C# #if DEBUG
    我对CSS vertical-align的一些理解与认识(一)
    htmlparser使用例子(全) 转载
    【HtmlParser】HtmlParser使用
    HTMLParser 使用详解
    htmlparser源码简单分析
    利用OpenXml生成Word2007文档
  • 原文地址:https://www.cnblogs.com/liucysun/p/14314490.html
Copyright © 2011-2022 走看看