mysql模拟插入数据表

因为测试或者学习须要,咱们要常常向一个新建的数据表插入几百万行以上的数据来验证咱们的一些想法,好比索引的合理构建,表字段类型的设计等等,下面跟你们演示如何往一个新建的数据表插入N多条数据。函数

1.新建一个数据表,例如:学习

CREATE TABLE userinfo_uuid
(
    uuid varchar(36) NOT NULL,
    name varchar(64) NOT NULL DEFAULT '',
    email varchar(64) NOT NULL DEFAULT '',
    password varchar(64) NOT NULL DEFAULT '',
    dob date DEFAULT NULL,
    address varchar(255) NOT NULL DEFAULT '',
    city varchar(64) NOT NULL DEFAULT '',
    state_id tinyint unsigned NOT NULL DEFAULT '0',
    zip varchar(8) NOT NULL DEFAULT '',
    country_id smallint unsigned NOT NULL DEFAULT '0',
    gender enum('M','F') NOT NULL DEFAULT 'M',
    account_type varchar(32) NOT NULL DEFAULT '',
    verified tinyint NOT NULL DEFAULT '0',
    allow_mall tinyint unsigned NOT NULL DEFAULT '0',
    parrent_account int unsigned NOT NULL DEFAULT '0',
    closest_airport varchar(3) NOT NULL DEFAULT '',
    PRIMARY KEY(uuid),
    UNIQUE KEY email (email),
    KEY country_id (country_id),
    KEY state_id (state_id),
    KEY state_id_2 (state_id,city,address)
)ENGINE=InnoDB;

2.由于这个表有不少varchar字段,咱们须要构建一个rand_string函数能够随意插入任意字符长度的字段测试

set global log_bin_trust_function_creators = 1;

DROP FUNCTION IF EXISTS rand_string;
DELIMITER $$
CREATE FUNCTION rand_string(n INT)
RETURNS VARCHAR(255)
BEGIN
    DECLARE chars_str varchar(100) DEFAULT 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    DECLARE return_str varchar(255) DEFAULT '';
    DECLARE i INT DEFAULT 0;
    WHILE i < n DO
        SET return_str = concat(return_str,substring(chars_str , FLOOR(1 + RAND()*62 ),1));
        SET i = i +1;
    END WHILE;
    RETURN return_str;
END $$
DELIMITER ;

3.建立存储过程ui

DELIMITER $$

     DROP PROCEDURE IF EXISTS `insert_userinfo_uuid`$$

     CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_userinfo_uuid`(IN item INTEGER)
     BEGIN
     DECLARE counter INT;
     SET counter = item;
     WHILE counter >= 1 DO
     insert into userinfo (uuid,name,email,password,dob,address,city,state_id,zip,country_id,gender,account_type,verified,allow_mall,parrent_account,closest_airport)
         values(uuid(),rand_string(64), rand_string(64), rand_string(64), '2010-10-10', rand_string(255), rand_string(64), ceil(rand() * 100), rand_string(8),
          ceil(rand() * 100), 'M', rand_string(32), 0, 0, 0, rand_string(3));
     SET counter = counter - 1;
     END WHILE;
     END$$

     DELIMITER ;

4.最后调用N屡次达到插入N条记录spa

call `insert_userinfo_uuid`(1000000);
相关文章
相关标签/搜索