mysql> show VARIABLES like '%max_allowed_packet%'; +--------------------------+------------+ | Variable_name | Value | +--------------------------+------------+ | max_allowed_packet | 1048576 | | slave_max_allowed_packet | 1073741824 | +--------------------------+------------+ 2 rows in set mysql> set global max_allowed_packet = 1024*1024*10; Query OK, 0 rows affected
public static void main(String[] args) throws IOException { FileWriter out = new FileWriter(new File("D://xxxxxxx//orders.txt")); for (int i = 0; i < 10000000; i++) { out.write( "vaule1,vaule2,vaule3,vaule4,vaule5,vaule6,vaule7,vaule8,vaule9,vaule10,vaule11,vaule12,vaule13,vaule14,vaule15,vaule16,vaule17,vaule18"); out.write(System.getProperty("line.separator")); } out.close(); }
ByteBuffer byteBuffer = ByteBuffer.allocate(buffSize); // 申請一個緩存區 long endPosition = batchFileSize + startPosition - buffSize;// 子文件結束位置 long startTime, endTime; for (int i = 0; i < count; i++) { startTime = System.currentTimeMillis(); if (i + 1 != count) { int read = inputChannel.read(byteBuffer, endPosition);// 讀取數據 readW: while (read != -1) { byteBuffer.flip();// 切換讀模式 byte[] array = byteBuffer.array(); for (int j = 0; j < array.length; j++) { byte b = array[j]; if (b == 10 || b == 13) { // 判斷\n\r endPosition += j; break readW; } } endPosition += buffSize; byteBuffer.clear(); // 重置緩存塊指針 read = inputChannel.read(byteBuffer, endPosition); } } else { endPosition = fileSize; // 最後一個文件直接指向文件末尾 } ...省略,更多能夠查看Github完整代碼... }
經過insert(...)values(...),(...)的方式批次插入數據,部分代碼以下:javascript
// 保存訂單和解析位置保證在一個事務中 SqlSession session = sqlSessionFactory.openSession(); try { long startTime = System.currentTimeMillis(); FielAnalysisMapper fielAnalysisMapper = session.getMapper(FielAnalysisMapper.class); FileOrderMapper fileOrderMapper = session.getMapper(FileOrderMapper.class); fileOrderMapper.batchInsert(orderList); // 更新上次解析到的位置,同時指定更新時間 fileAnalysis.setPosition(endPosition + 1); fileAnalysis.setStatus("3"); fileAnalysis.setUpdTime(new Date()); fielAnalysisMapper.updateFileAnalysis(fileAnalysis); session.commit(); long endTime = System.currentTimeMillis(); System.out.println("===插入數據花費:" + (endTime - startTime) + "ms==="); } catch (Exception e) { session.rollback(); } finally { session.close(); } ...省略,更多能夠查看Github完整代碼...
https://my.oschina.net/OutOfMemory/blog/3117737java
點擊「閱讀原文」和棧長學更多~mysql