MySQL大批量数据插入
公司有一個項目,需要頻繁的插入數(shù)據(jù)到MySQL數(shù)據(jù)庫中,設(shè)計目標(biāo)要求能支持平均每秒插入1000條數(shù)據(jù)以上。目前功能已經(jīng)實(shí)現(xiàn),不過一做壓力測試,發(fā)現(xiàn)數(shù)據(jù)庫成為瓶頸,每秒僅能插入100多條數(shù)據(jù),遠(yuǎn)遠(yuǎn)達(dá)不到設(shè)計目標(biāo)。
到MySQL官方網(wǎng)站查了查資料,發(fā)現(xiàn)MySQL支持在一條INSERT語句中插入多條記錄,格式如下:
INSERT table_name (column1, column2, ..., columnN)
VALUES (rec1_val1, rec1_val2, ..., rec1_valN),
(rec2_val1, rec2_val2, ..., rec2_valN),
... ...
(recM_val1, recM_val2, ..., recM_valN);
按MySQL官方網(wǎng)站,用這種方法一次插入多條數(shù)據(jù),速度比一條一條插入要快很多。在一臺開發(fā)用的筆記本電腦上做了個測試,果然速度驚人。
測試環(huán)境:DELL Latitude D630, CPU T7250 @ 2.00GHz, 內(nèi)存 2G。Windows XP Pro中文版SP2,MySQL 5.0 for Windows。
MySQL是新安裝的,建立了一個名為test的數(shù)據(jù)庫,在test數(shù)據(jù)庫建了一個t_integer表,共兩個字段:test_id和test_value,兩個字段都是INTEGER類型,其中test_id是Primary Key。
準(zhǔn)備了兩個SQL腳本文件(寫了個小程序生成的),內(nèi)容分別如下:
-- test1.sql
TRUNCATE TABLE t_integer;
INSERT t_integer (test_id, test_value)
VALUES (1, 1234),
(2, 1234),
(3, 1234),
(4, 1234),
(5, 1234),
(6, 1234),
... ...
(9997, 1234),
(9998, 1234),
(9999, 1234),
(10000, 1234);
-- test2.sql
TRUNCATE TABLE t_integer;
INSERT t_integer (test_id, test_value) VALUES (1, 1234);
INSERT t_integer (test_id, test_value) VALUES (2, 1234);
INSERT t_integer (test_id, test_value) VALUES (3, 1234);
INSERT t_integer (test_id, test_value) VALUES (4, 1234);
INSERT t_integer (test_id, test_value) VALUES (5, 1234);
INSERT t_integer (test_id, test_value) VALUES (6, 1234);
... ...
INSERT t_integer (test_id, test_value) VALUES (9997, 1234);
INSERT t_integer (test_id, test_value) VALUES (9998, 1234);
INSERT t_integer (test_id, test_value) VALUES (9999, 1234);
INSERT t_integer (test_id, test_value) VALUES (10000, 1234);
以上兩個腳本通過mysql命令行運(yùn)行,分別耗時0.44秒和136.14秒,相差達(dá)300倍。
基于這個思路,只要將需插入的數(shù)據(jù)進(jìn)行合并處理,應(yīng)該可以輕松達(dá)到每秒1000條的設(shè)計要求了。
補(bǔ)充:以上的測試都是在InnoDB表引擎基礎(chǔ)上進(jìn)行的,而且是AUTOCOMMIT=1,對比下來速度差異非常顯著。之后我將t_integer表引擎設(shè)置為MyISAM進(jìn)行測試,test1.sql執(zhí)行時間為0.11秒,test2.sql為1.64秒。
補(bǔ)充2:以上的測試均為單機(jī)測試,之后做了跨機(jī)器的測試,測試客戶端(運(yùn)行腳本的機(jī)器)和服務(wù)器是不同機(jī)器,服務(wù)器是另一臺筆記本,比單機(jī)測試時配置要好些。做跨機(jī)器的測試時,發(fā)現(xiàn)不管是InnoDB還是MyISAM,test1.sql速度都在0.4秒左右,而test2.sql在InnoDB時且AUTOCOMMIT=1時要80多秒,而設(shè)置為MyISAM時也要20多秒。
轉(zhuǎn)載于:https://blog.51cto.com/ylj798/1061860
總結(jié)
以上是生活随笔為你收集整理的MySQL大批量数据插入的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html微博首页布局,html+css微
- 下一篇: 三级分类菜单的数据库设计