MySQL大批量数据插入
公司有一個項目,需要頻繁的插入數據到MySQL數據庫中,設計目標要求能支持平均每秒插入1000條數據以上。目前功能已經實現,不過一做壓力測試,發現數據庫成為瓶頸,每秒僅能插入100多條數據,遠遠達不到設計目標。
到MySQL官方網站查了查資料,發現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官方網站,用這種方法一次插入多條數據,速度比一條一條插入要快很多。在一臺開發用的筆記本電腦上做了個測試,果然速度驚人。
測試環境:DELL Latitude D630, CPU T7250 @ 2.00GHz, 內存 2G。Windows XP Pro中文版SP2,MySQL 5.0 for Windows。
MySQL是新安裝的,建立了一個名為test的數據庫,在test數據庫建了一個t_integer表,共兩個字段:test_id和test_value,兩個字段都是INTEGER類型,其中test_id是Primary Key。
準備了兩個SQL腳本文件(寫了個小程序生成的),內容分別如下:
-- 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命令行運行,分別耗時0.44秒和136.14秒,相差達300倍。
基于這個思路,只要將需插入的數據進行合并處理,應該可以輕松達到每秒1000條的設計要求了。
補充:以上的測試都是在InnoDB表引擎基礎上進行的,而且是AUTOCOMMIT=1,對比下來速度差異非常顯著。之后我將t_integer表引擎設置為MyISAM進行測試,test1.sql執行時間為0.11秒,test2.sql為1.64秒。
補充2:以上的測試均為單機測試,之后做了跨機器的測試,測試客戶端(運行腳本的機器)和服務器是不同機器,服務器是另一臺筆記本,比單機測試時配置要好些。做跨機器的測試時,發現不管是InnoDB還是MyISAM,test1.sql速度都在0.4秒左右,而test2.sql在InnoDB時且AUTOCOMMIT=1時要80多秒,而設置為MyISAM時也要20多秒。
轉載于:https://blog.51cto.com/ylj798/1061860
總結
以上是生活随笔為你收集整理的MySQL大批量数据插入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html微博首页布局,html+css微
- 下一篇: linux sar 历史负载,查看负载、