java 使用jdbc向mysql数据库中插入1亿条数据

来源:互联网 发布:中国网络书画论坛 编辑:程序博客网 时间:2024/05/22 10:24

http://blog.csdn.net/home_zhang/article/details/50836253

[java] view plain copy
  1. <span style="font-size:14px;"><span style="font-size:14px;">package com.ddx.zhang;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.UUID;  
  5.   
  6. public class JDBCTest {  
  7.     public static void main(String[] args) throws SQLException {  
  8.         try {  
  9.             Class.forName("com.mysql.jdbc.Driver");  
  10.         } catch (ClassNotFoundException e) {  
  11.             e.printStackTrace();  
  12.         }  
  13.   
  14.         java.sql.Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost/test""root""123456");  
  15.   
  16.         java.sql.Statement stmt = conn.createStatement();  
  17.   
  18.         int total = 10000;  
  19.         System.out.println("====start=====");  
  20.           
  21.         long start = System.currentTimeMillis();  
  22.         // 测试插入数据库的功能:  
  23.         for (int n = 0; n < 1000; n++) {  
  24.             StringBuffer sBuffer = new StringBuffer(" insert into student(user_name) values ");  
  25.             for (int i = 0; i < total; i++) {  
  26.                 String userName = UUID.randomUUID().toString();  
  27.                 if (i == total - 1) {  
  28.                     sBuffer.append("('" + userName + "');");  
  29.                 } else {  
  30.                     sBuffer.append("('" + userName + "'),");  
  31.                 }  
  32.             }  
  33.             System.out.println("第" + n + "次插入1万条数据!");  
  34.             stmt.executeUpdate(sBuffer.toString());  
  35.         }  
  36.           
  37.         long end = System.currentTimeMillis();  
  38.   
  39.         System.out.println("run time:" + (end - start));  
  40.         stmt.close();  
  41.         conn.close();  
  42.     }  
  43. }  
  44. </span></span>  


运行结束所需要的时间:247828ms,为247.828s=4.13m

将每次插入条数total修改为25000,n<400 ,运行结束所需要的时间为:209958ms,为209.958s=3.4993m


比较之后,选择用每次插入25000条,循环400次的方式插入,运行10次,既可插入1亿条数据。总花费时间也就10几分钟


表的sql脚本如下:

CREATE TABLE `student` (
  `id` bigint(20) NOT NULL auto_increment COMMENT '主键',
  `user_name` varchar(255) default NULL COMMENT '姓名',
  `add_time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP COMMENT '添加时间',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


阅读全文
0 0
原创粉丝点击