【原创】在thinkphp中向另一个数据库批量插入与更新

批量插入1000万条数据:

public function insertData(){
    set_time_limit(0);
    ini_set("memory_limit",-1);
    $startTime = time();

    // 插入100w条数据,测试用时 109s
    // 插入1000w条数据,测试用时 1339s
    $num = 10000000;
    for($i=1;$i <= $num;$i++){
        $insertData[] = array(
            'name'=>'name_'.$i,
            'sex'=>mt_rand(0, 1)
        );
    }
    $db = Db::connect(config('DB_CONFIG'));
    $onceNum = 1000;
    $limit = ceil($num/$onceNum);
    try{
        for($i = 1;$i <= $limit;$i++){
            $offset = ($i-1) * $onceNum;
            $data = array_slice($insertData,$offset,$onceNum);
            $db->name('user')->insertAll($data);
        }
        $endTime = time();
        $useTime = $endTime - $startTime;
        echo "$num 数据插入用时:$useTime 秒";
    }catch (\Exception $e){
        echo "出现异常:".$e->getMessage();
    }
}

批量更新1000万条数据
  public function insertNum(){
        set_time_limit(0);
        ini_set("memory_limit",-1);
        $startTime = time();
        $userModel = new Tuser();
        $num = 10000000;
        for($i=1;$i <= $num;$i++){
            $updateData[] = array(
                'id'=>$i,
                'num'=>mt_rand(0,100000)
            );
        }
        $onceNum = 1000;
        $limit = ceil($num/$onceNum);
        try{
            for($i = 1;$i <= $limit;$i++){
                $offset = ($i-1) * $onceNum;
                $data = array_slice($updateData,$offset,$onceNum);
                $userModel->saveAll($data);
            }
            $endTime = time();
            $useTime = $endTime - $startTime;
            echo "$num 条数据更新用时:$useTime 秒";
        }catch (\Exception $e){
            echo "出现异常:".$e->getMessage();
        }
    }
其中Tuser.php模型:
class Tuser extends Model
{
    protected $connection = array(
        // 数据库类型
        'type'        => 'mysql',
        // 服务器地址
        'hostname'    => '127.0.0.1',
        // 数据库名
        'database'    => 'test',
        // 数据库用户名
        'username'    => 'root',
        // 数据库密码
        'password'    => 'xxx',
        // 数据库编码默认采用utf8
        'charset'     => 'utf8',
        // 数据库表前缀
        'prefix'      => 'test_',
    );
    // 定义主键和数据表
    protected $pk = 'id';
    protected $table = 'test_user';
}
app.php中数据库配置:
'DB_CONFIG'=>array(
    // 数据库类型
    'type'        => 'mysql',
    // 服务器地址
    'hostname'    => '127.0.0.1',
    // 数据库名
    'database'    => 'test',
    // 数据库用户名
    'username'    => 'root',
    // 数据库密码
    'password'    => 'xxx',
    // 数据库编码默认采用utf8
    'charset'     => 'utf8',
    // 数据库表前缀
    'prefix'      => 'test_',
)

 

点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注