mysql存儲中使用while批量插入數據(批量提交和單個提交的區別)

批量提交

while 語句寫法:

    while '條件' do
            循環體語句;
    end while;

完整寫法

drop procedure if exists test_insert;
delimiter $$
create procedure test_insert(n int)
    begin
    declare v int default 0;
    set AUTOCOMMIT = 0;
    while v < n
        do
                insert into test(second_key, text, field_4,status, create_date)
                values ((v*10),
                concat('t',v),
                substring(md5(rand()), 1, 10),
                'good',
                adddate('1970-01-01', rand(v) * 10000));
        set v = v + 1;
     end while;
      set AUTOCOMMIT = 1;
end$$
delimiter ;

查看、刪除存儲過程:

mysql> show procedure status like 'test_insert';
mysql> show create procedure test_insert\G;
mysql> drop procedure if exists test_insert;

創建表

CREATE TABLE test (
id INT NOT NULL AUTO_INCREMENT,
second_key INT,
text VARCHAR(20),
field_4 VARCHAR(20),
status VARCHAR(10),
create_date date,
PRIMARY KEY (id),
KEY idx_second_key (second_key)
) Engine=InnoDB CHARSET=utf8;

插入100萬條數據

mysql> call test_insert(1000000);
Query OK, 0 rows affected (31.86 sec)

單個提交

完整寫法

drop procedure if exists test_insert;
delimiter $$
create procedure test_insert(n int)
    begin
    declare v int default 0;
    while v < n
        do
                insert into test(second_key, text, field_4,status, create_date)
                values ((v*10),
                concat('t',v),
                substring(md5(rand()), 1, 10),
                'good',
                adddate('1970-01-01', rand(v) * 10000));
        set v = v + 1;
     end while;
end$$
delimiter ;

插入1萬條數據

mysql> call test_insert(10000);
Query OK, 1 row affected (1 min 8.52 sec)

打開另一個窗口查看

mysql> select count(*) from test.test;
+----------+
| count(*) |
+----------+
|     1428 |
+----------+
1 row in set (0.00 sec)
mysql> select count(*) from test.test;
+----------+
| count(*) |
+----------+
|     1598 |
+----------+
1 row in set (0.00 sec)
mysql> select count(*) from test.test;
+----------+
| count(*) |
+----------+
|     1721 |
+----------+
1 row in set (0.00 sec)
mysql> select count(*) from test.test;
+----------+
| count(*) |
+----------+
|     1983 |
+----------+
1 row in set (0.00 sec)

結論

批量提交100萬條數據用瞭30秒,單個提交1萬條數據用瞭1分鐘,對比發現,批量提交的效率遠大於單個提交的效率

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。 

推薦閱讀: