zoukankan      html  css  js  c++  java
  • laravel框架存储50万条数据

    <?php
    
    namespace AppConsoleCommands;
    
    use IlluminateConsoleCommand;
    use IlluminateSupportFacadesDB;
    
    /**
     * 插入50W数据脚本
     * Class CreateDataCommand
     * @package AppConsoleCommands
     */
    class CreateDataCommand extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'command:create_data';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'Command description';
    
        /**
         * Create a new command instance.
         *
         * @return void
         */
        public function __construct()
        {
            parent::__construct();
        }
    
        const TABLE_NAME = 'person_';
    
        const COLUMN_NAME_ARR = ['account','name','area','title','motto'];
    
        const RANDOM_STRING='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    
        /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
            $startTime = time();
            for($i = 0; $i< 500000; $i++){
    
                $this->insertData($i);
    
                if($i % 1000 == 1){
                    echo ".";
                }
    
            }
    
            $endTime = time();
            echo "success 
    ";
            echo "time:".($endTime - $startTime);
        }
    
        /**
         * 插入数据
         * 定义属性 static
         * @param $i
         */
    
        private function insertData($i){
    
    
    
            foreach(self::COLUMN_NAME_ARR as $columnName){
                $params[$columnName] = $this->getRandomString(10);
            }
            $isSuccess = DB::table($this->getTableName($i))->insert($params);
            if(!$isSuccess){
                echo "insert fail!
    ";
            }
        }
    
        /**
         * 获取表名
         * @param $i
         * @return string
         */
        private function getTableName($i){
            return self::TABLE_NAME.($i%10);
        }
    
        /**
         * 获取随机字符
         * @param $length
         * @return string
         */
        private function getRandomString($length){
            $result = "";
            for($i=0; $i<$length-1; $i++){
                $result .= self::RANDOM_STRING[mt_rand(0,strlen(self::RANDOM_STRING)-1)];
            }
            return $result;
        }
    }

    然后进入根目录执行命令

    command:create_data
    然后,数据就进入数据库了。
  • 相关阅读:
    最全的CSS浏览器兼容问题整理
    游戏设计源概念——学习
    如何将数据从 Excel 导入到 SQL Server
    IE8网页显示不正常 用”兼容性视图”搞定
    Lua概念定义及相关资料
    谈谈主策划需要的能力
    微博营销实战经验总结
    创业公司CEO每天应该做的13件事
    2011营销往哪一个风向吹
    [转]网店博客营销之微博实战技巧:还没有做微博的掌柜看过来
  • 原文地址:https://www.cnblogs.com/stj123/p/10896024.html
Copyright © 2011-2022 走看看