review代碼發現,同事mysql批量插入數據的實現方法是,用for循環遍歷,將列表每個數據單次插入。相當於批量插入N條數據,進行了n次的數據庫連接和插入操作。
底層有批量插入的方法,但是會有問題,所以已經停用,看下面實現是,取到一個數據庫連接,來處理后面所有的插入操作。若這個列表ops所有的sql語句執行的數據庫都是同一個的話,就沒什么問題,若里面存在散庫的情況,只要跟第一個不在同一個庫的,都會執行失敗。
public void insertBatch(List<OpBatchUpdate> ops) throws SQLException { if(ops != null && ops.size() != 0) { OpBatchUpdate firstOp = (OpBatchUpdate)ops.get(0); if(firstOp.bizName != null && firstOp.bizName.trim().length() != 0) { PreparedStatement ps = null; Connection conn = null; long begin = 0L; try { begin = this.sqlBegin(); conn = this.getConn('w', firstOp);//取第一個來監理數據庫連接 Iterator i$ = ops.iterator(); while(i$.hasNext()) { OpBatchUpdate opb = (OpBatchUpdate)i$.next(); ps = conn.prepareStatement(opb.getSql()); opb.setParam(ps); ps.executeUpdate(); if(ps != null) { ps.close(); } } } finally { this.closeRSC((ResultSet)null, ps, conn); this.sqlEnd("excutebatch sql,", begin); } } else { throw new SQLException(" ----- the bizName of the first opbatchupdate object can\'t null -------------"); } } else { throw new SQLException(" ----- the opbatchupdate list can\'t null -------------"); } }
對同一個庫的同一個表進行批量插入操作。有兩種方法:
以表smily_test為例:
CREATE TABLE `smily_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `uid` int(11) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
1. for循環,將數據一條條插入。
insert into smily_test (uid) values(1); insert into smily_test (uid) values(2); insert into smily_test (uid) values(3);
2. 單次批量插入。
insert into smily_test (uid) values(1),(2),(3);
通過profile分析(查看mysql語句運行時間)得知:
方法2比方法1的效率高。
+----------+------------+------------------------------------------------+ | Query_ID | Duration | Query | +----------+------------+------------------------------------------------+ | 5 | 0.00079800 | insert into smily_test (uid) values(1) | | 6 | 0.00081300 | insert into smily_test (uid) values(2) | | 7 | 0.00078700 | insert into smily_test (uid) values(3) | | 8 | 0.00083200 | insert into smily_test (uid) values(1),(2),(3) | +----------+------------+------------------------------------------------+
總結:
方法1:執行效率偏低,會進行多次數據庫的連接,比較耗時。但是適用於散庫、散表的情況。
若數據在不同的庫,則只能進行多次數據庫連接。
若列表數據要插入同1個庫的不同的表中,則可以選擇1次數據庫連接,多次數據插入執行的方式。
方法2:執行時間短,只適用於對同一個庫同一個表批量插入數據的情況。